I have the following CSS code which works fine to fit an image to its container while keeping the image size ratio.
img { /* ASSUMING THE IMAGE IS WIDER THAN 150PX OR HIGHER THAN 100PX */
max-height: 100%;
max-width: 100%;
}
div.mydiv1 {
width: 150px;
height: 100px;
background-color:red;
}
However, if the image is both shorter and narrower than the container, it does stretch to fit (keeping size ratio). Is there a way to do this?
Here a fiddle... http://jsfiddle.net/many_tentacles/uz3e7/
Instead of using an img tag you might find it easier to achieve your desired functionality by using the css attribute background: url('path/to/img') no-repeat ... and background-size: contain
So for example in the css
div.mydiv3 {
width: 300px;
height: 70px;
background-color:red;
background: url("http://cdn-careers.sstatic.net/careers/gethired/img/careers2-ad-header-so-crop.png") no-repeat red;
background-size: contain;
}
and the HTML
<div class="mydiv3"></div>
I updated your fiddle. http://jsfiddle.net/uz3e7/4/
The closest I think you are going to get is to set the either the height or width (which ever one you want to math it's container) to 100% and the other to auto. Adding an overflow: hidden; to the container will keep the image from overlapping anything else. That is to say:
img {
max-height: auto;
width: 100%;
}
div {
overflow: hidden;
}
See this fiddle to see what I mean. I also agree with cpreid that what you seem to be asking isn't possible. Not without changing the size/shape of the parent container.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With