This blog post is mostly a bookmark for myself, as I’ve spent too much time researching this problem in the past: Can you ‘contain‘ a <div> or similar element the same way object-fit works with replaced media (images/videos), with nothing but CSS?

It turns out, as I finally learned in a 6-year old StackOverflow reply, the answer is yes*:

This is pretty clever! It’s using a combination of vh and vw units to do the trick. That does mean though that it works best when you’re aligning against the whole viewport. But if you must subtract a header or footer height, you can use calc to achieve it.

For elements that don’t need to be contained, or if you only need containment on one axis (flexbox!), I recommend Chris’ aspect-ratio write-up.

Reply with a tweet or leave a Webmention. Both will appear here.