html - Vertically center image when image is higher than container -


i have responsive design header image placed in container. image has width:100%; , height:auto; grows enlarge viewport. don't want exceed height container has max-height. image still grows bottom part cut off because aligns top of container.

i image stay vertically centered in it's container parts of image cut off @ top , @ bottom. outcome should this:

verticaly centered image

the header images uploaded users might have different heights therefore cannot work specific pixel-values. there css-solution or have use javascript?

here code:

.wrapper {    width: 90%;    max-width: 600px;    margin: 1em auto;    background-color: #e9adad;  }  .container {    text-align: center;    height: auto;    line-height: 200px;    max-height: 200px;    overflow: hidden;  }  img {    width: 100%;    height: auto !important;    vertical-align: middle;  }
<div class="wrapper">    <div class="container">      <img src="http://placehold.it/600x300/c00000/ffffff&text=image+vertically+centered">    </div>  </div>

and prepared fiddle.

you can use absolute positioning image , negative top/bottom values , margin:auto; verticaly center image in container :

.wrapper {    width: 90%;    max-width: 600px;    margin: 1em auto;    background-color: #e9adad;    max-height: 200px;  }  .container {    position:relative;    padding-bottom:40%;    overflow: hidden;  }  img {    position:absolute;    top:-50%; bottom:-50%;    margin:auto;    width: 100%;    height: auto;  }
<div class="wrapper">    <div class="container">      <img src="http://placehold.it/600x300/c00000/ffffff&text=image+vertically+centered">    </div>  </div>


Comments