Sam

🚀 Start Here

# Why isn't object-fit doing anything? CSS Diaries

📅 Tue, August 22nd 2023
topics: #css

⚠️ All typical warnings apply when you’re taking web-dev advice from me ⚠️

What’s Object Fit?

You can use it to fill a container with an image (or any replace element ).

Unless you’re exceptionally lucky, your images don’t always fit perfectly into the containers you need them to.

For example, here I’m trying to get this egg to fit into a nice round parent. But it’s not the right size.

The photo doesn’t fit nicely in the circle

Even a cheeky attempt to replicate the curvature with “border-radius” ends badly,

The photo still doesn’t fit nicely in the circle

But with object-fit: cover;, magic!

The photo fits nicely into the circle

That’s just the start of object-fit’s powers, read more here.

You can check this demo here.

But wait it still doesn’t work for me

Fast forward to me anguishing for 30 minutes about why the card images on my home page aren’t filling the card!

The card isn’t filled

MDN Docs couldn’t help.

Turns out, for object-fit to work, the image itself needs both a height & a width set. Without them, no fit. In most cases, you will probably be setting to 100% for both, to match the parent size. I’m not sure why that’s not the default. Alas, I hope this will save you a few minutes of despair.