I have a responsive design with a header image that fits in a container. The image has a width:100%; and height:auto; , therefore, it increases with increasing viewing area. I do not want to exceed a certain height, so the container has max-height . The image is still growing, but now the bottom is cropped because it aligns with the top of the container.
I want the image to remain vertically centered in the container, so that parts of the image are cut off from above and below. The result should look like this:

Header images are uploaded by users, so they can have different heights, so I canβt work with certain pixel values. Is there a CSS solution for this or do I need 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 .
source share