Jon McPherson Jon McPherson - 3 months ago 16
CSS Question

CSS: How can I set image size relative to parent height?

I am 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 (screenshots), and I want to put them into a 200px width, 180px height 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:

http://jsfiddle.net/f9krj/2/

HTML

<a class="image_container" href="http://www.skintype.ca/assets/background-x_large.jpg">
<img src="http://www.skintype.ca/assets/background-x_large.jpg" alt="" />
</a>


CSS

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?

Answer

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:

<div>
    <img src="http://lorempixel.com/300/160/nature/" />
</div>
<div>
    <img src="http://lorempixel.com/300/200/nature/" />
</div>
<div>
    <img src="http://lorempixel.com/200/300/nature/" />
</div>

And CSS:

div {
    width:200px;
    height:150px;
    position:relative;
    display:inline-block;
    overflow:hidden;
}

div > img {
    position:absolute;
    top:50%;
    min-height:100%;
    display:block;
    left:50%;
    -webkit-transform: translate(-50%, -50%);
    min-width:100%;
}

Voila! Working: http://jsfiddle.net/shekhardesigner/aYrhG/