object-fit and object-position
Published on
Whether it’s because of dynamic content or some other reason, sometimes we have inconsistent image sizes.
If we use CSS to control the size of those images, that can lead to distortion:
In these situations, object-fit
can come in handy, where we can “fit” the image to the size we’ve declared using the cover
and contain
keywords, which work in a similar way as the same keywords with background-size
.
We also have a few other keywords we can use:
fill
- The default behaviornone
- The image will keep it’s intrinsic size, even if the available space for it is larger or smallerscale-down
- It won’t make the image bigger to fill extra space, but if the space available is smaller than the intrinsic size, it will shrink the image in the same way to howcontain
works.
We can position the images as well
When the images are being cropped (or there is extra room available), we can change where the image is positioned using object-position
, similar to how background-position
works, with one important difference: center center
is the default for object-position
.