Contain an image within a div?
Use max width and max height. It will keep the aspect ratio
#container img
{
max-width: 250px;
max-height: 250px;
}
http://jsfiddle.net/rV77g/
Since you don't want stretching (all of the other answers ignore that) you can simply set max-width and max-height like in my jsFiddle edit.
#container img {
max-height: 250px;
max-width: 250px;
}
See my example with an image that isn't a square, it doesn't stretch
You have to style the image like this
#container img{width:100%;}
and the container with hidden overflow:
#container{width:250px; height:250px; overflow:hidden; border:1px solid #000;}
object-fit
, behaves like background-size
, solving the issue of scaling images up and down to fit.
The object-fit CSS property specifies how the contents of a replaced element should be fitted to the box established by its used height and width.
https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
.cover img {
width: 100%;
height: 100%;
object-fit: cover;
overflow: hidden;
}
Browser Support
There's no IE support, and support in Edge begins at v16, only for img
element: https://caniuse.com/#search=object-fit
The bfred-it/object-fit-images polyfill works very well for me in IE11, tested on Browserstack: demo.
Alternative without polyfill using an image in SVG
For Edge pre v16, and ie9, ie10, ie11:
You can crop and scale any image using CSS
object-fit
andobject-position
. However, these properties are only supported in the latest version of MS Edge as well as all other modern browsers.If you need to crop and scale an image in Internet Explorer and provide support back to IE9, you can do that by wrapping the image in an
<svg>
, and using theviewBox
andpreserveAspectRatio
attributes to do whatobject-fit
andobject-position
do.http://www.sarasoueidan.com/blog/svg-object-fit/#summary-recap
(The author explains the technique thoroughly, and duplicating the detail here would be impractical.)