I want to contain an image into a 250 x 250 div, forcing the image to resize but not stretch. How can I do this? By the way, the image will usually be bigger than the div itself, which is why resizing comes into the picture.
<div id = "container"> <img src = "whatever" /> </div> #container { width:250px; height:250px; border:1px solid #000; }
Here's a jsfiddle which someone can edit:
http://jsfiddle.net/rV77g/
To auto-resize an image or a video to fit in a div container use object-fit property. It is used to specify how an image or video fits in the container. object-fit property: This property is used to specify how an image or video resize and fit the container.
How to fit image without stretching and maintain aspect ratio? Answer: If you want to use the image as a CSS background, there is an elegant solution. Simply use cover or contain in the background-size CSS3 property. contain will give you a scaled-down image.
One of the simplest ways to resize an image in the HTML is using the height and width attributes on the img tag. These values specify the height and width of the image element. The values are set in px i.e. CSS pixels. For example, the original image is 640×960.
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; }
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.
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.)
Use max width and max height. It will keep the aspect ratio
#container img { max-width: 250px; max-height: 250px; }
http://jsfiddle.net/rV77g/
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