[html] CSS - how to make image container width fixed and height auto stretched

I've go some html code like this:

 <div class="item">
    <img src="...">
 </div>

And css code like this:

img {
    max-width: 100%;
    height: auto;
}

.item {
    width: 120px;
    height: 120px;
    height: auto;
    float: left;
    margin: 3px;
    padding: 3px;
}

What I would like to do is to make the img display using the div's width and stretch its height. I also want the div stretch itself to fit the img. Is that possible?

This question is related to html css

The answer is


No, you can't make the img stretch to fit the div and simultaneously achieve the inverse. You would have an infinite resizing loop. However, you could take some notes from other answers and implement some min and max dimensions but that wasn't the question.

You need to decide if your image will scale to fit its parent or if you want the div to expand to fit its child img.

Using this block tells me you want the image size to be variable so the parent div is the width an image scales to. height: auto is going to keep your image aspect ratio in tact. if you want to stretch the height it needs to be 100% like this fiddle.

img {
    width: 100%;
    height: auto;
}

http://jsfiddle.net/D8uUd/1/


Try width:inherit to make the image take the width of it's container <div>. It will stretch/shrink it's height to maintain proportion. Don't set the height in the <div>, it will size to fit the image height.

img {
    width:inherit;
}

.item {
    border:1px solid pink;
    width: 120px;
    float: left;
    margin: 3px;
    padding: 3px;
}

JSFiddle example