Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically center image when image is higher than container

I have a responsive design with a header image which is placed in a container. The image has width:100%; and height:auto; so it grows as you enlarge the viewport. I don't want to exceed a certain height so the container has a max-height. The image still grows but now the bottom part is cut off now because it aligns to the top of the container.

I would like the image to stay vertically centered in it's container so that parts of the image are cut off at the top and at the bottom. The outcome should look like this:

verticaly centered image

The header images are uploaded by users so they might have different heights therefore I cannot work with specific pixel-values. Is there a CSS-solution for this or do I have to use JavaScript?

Here is the 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 I prepared a fiddle.

like image 506
zork media Avatar asked May 08 '15 11:05

zork media


People also ask

How do I center an image vertically in HTML?

Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.

How do you vertically align an image in a table cell?

Answer: Use the CSS vertical-align Property You can align an image vertically center inside a <div> by using the CSS vertical-align property in combination with the display: table-cell; on the containing div element.


1 Answers

You can use absolute positioning for your image , negative top/bottom values and margin:auto; to verticaly center the image in the 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>
like image 154
web-tiki Avatar answered Oct 29 '22 14:10

web-tiki