Jon McPherson Jon McPherson - 1 year ago 165
CSS Question

CSS set image size relative to parent height

I have been stumped trying to figure out how to re-size an image so that it keeps it ratio of width to height, but gets re-sized until the height of the image matches the height of the containing div. I have these images that are pretty large and long (screen shots), and I want to put them into a 200w 180h div for display and without re-sizing the images manually. To make this look good, the sides of the image need to overflow and be hidden with the containing div. This is what I have so far.


<a class="image_container" href="">
<img src="" alt="" />


a.image_container {
background-color: #999;
width: 200px;
height: 180px;
display: inline-block;
overflow: hidden;

a.image_container img {
width: 100%;

As you can see, there is grey color showing on the images parent container which should not be shown at all. In order for that container to be filled completely, the width needs to be overflowed equally on both sides. Is this possible?
Is it also possible to account for an image that is also too tall?

I remember seeing a cool codepen on absolute centering in css. I'll play around with that, but I would appreciate any help! thanks!

Answer Source

If you are ready to opt for CSS3, you can use css3 translate property. Resize based on whatever is bigger. If your height is bigger and width is smaller than container, width will be stretch to 100% and height will be trimmed from both side. Same goes for larger width as well.

Your need, HTML:

    <img src="" />
    <img src="" />
    <img src="" />

And CSS:

div {

div > img {
    -webkit-transform: translate(-50%, -50%);

Voila! Working:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download