Object-fit and how it can change your life

Ok, so maybe the title is a but dramatic, but I love coming across a way of doing something in CSS that just works, and makes perfect sense. How many times have we come across quirks in our code (talk about ghost space, am I right?) that require some sort of mini-hack to regulate? But sometimes, CSS can actually be quite intuitive, and the object-fit property is one of those rare instances. It’s one of those cases where you want something specific to happen, so you hit up the MDN documentation on it, and prepare yourself for 10 or 20 lines of code to achieve what you want, but alas, only need one simple property, and you think to yourself, “the Dev Gods have been kind to me this fateful evening”.

Before we dive deeper into object-fit, it is worth noting that it is lacking browser support from Internet Explorer and Edge.

Image source: https://tympanus.net/codrops/css_reference/object-fit/

So, object-fit accepts many different values, and they each have pretty specific use cases. The one that I find myself using the most is object-fit: cover. This causes the image to fill the height and width if it’s container while still maintaining its aspect ratio. When you have multiple images for, say, a gallery or portfolio section, and you want them each to be cropped to a certain size but need that div to remain dynamic, the “cover” value achieves this nicely.

Next, is fill. This is the default value, where the image stretches in any way it needs to in order to fill its container.

Similarly, is none. The image will retain its original size despite the height and width of the container.

Another useful value is contain. The image will get larger or smaller in order to fit in its container while maintaining its aspect ratio.

And lastly, scale-down combines none and contain to choose whichever image is smallest. I haven’t found a use for this yet, but I’m also less than a year into my development career so stay tuned! 
 More information can be found on the MDN website, and of course by playing around with the property! It’s a handy one to have in your toolbox, and as with most things, something I wish I knew about sooner.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.