CSS object-fit and object-position properties: Crop images embedded in HTML
object-position are used to specify the size and position of external media inserted into HTML, mainly the images within the
<img> tag, but also the content of the
The properties are not supported by Internet Explorer, therefore they are more useful for projects where it’s not that important.
object-position can be viewed as parallel to the image properties
background-position. Only that these are intended for elements inserted directly into HTML.
Let’s show it on a simple example.
We have the following HTML:
<img class="img img--cut" src="image-300x300.jpg"
width="300" height="200" alt="Image…">
And let’s explain:
- The image has natural dimensions of 300x300 pixels, but it is only allowed to occupy the height of 200 pixels in HTML, see the
object-fit:coverindicates that the image should be stretched over the entire area of the
<img>element so that there is no space left. See
object-position:bottomspecifies the alignment to the bottom edge of the
<img>element surface. See
Specifies how to fit the external media to an area specified by the
height properties in HTML or CSS.
This is very similar to embedding images to background using the
Defines where will be the element positioned by using
object-fit. It has exactly the same values as the
Let’s look at examples of values.
Use in practice
- Both properties are very useful for enforcing aspect ratio when we have images with different shapes and sizes saved on the server.
- Object-fit video background works as well. The same with iframe does not.
Support in browsers
Since the Edge explorer has been upgraded to the Chromium rendering engine, only Internet Explorer 11 does not support these properties.
By the time I am writing this article, Internet Explorer still has a significant share of users in some countries (like for example here, in the Czech Republic), so it will be necessary to sort out the fallback.
How to solve the problem in Internet Explorer:
- Instead of
object-positionembed the image to the background by using
background-position.Alternatively, you can play with the transform property and with absolute positioning (See StackOverflow).
- For IE11 use polyfill — fregante/object-fit-images. I do not recommend it much, because it slows down the rendering performance in the already slow Explorer.
- Detect a non-supporting browser (eg. using the Modernizr library) and deploy a workaround. For example, StackOverflow offers a solution to change
<svg>and resolve the problem in it.
Originally published at https://www.cssmine.com.