some css code

Forcing a div to retain aspect ratio, but also expand if there’s more content

I’ve just been stuck on a problem for ages, and that’s to keep at a specific aspect ratio (on mobile, tablet and desktop), but also to allow it to expand if there’s more content inside it.

Making a div maintain an aspect ratio is pretty easy. Give it a bottom padding of the ratio. So for 16/9 it’s 9/16*100 = 56, meaning your bottom padding should be 56%.

The problem is when you need content inside, and in my particular case I needed to align the content bottom left. Like this:

aspect ratio div bottom left

But, as soon as I use position absolute to align this content, it means the content will go outside the box if it’s really small, and I want it to push the box taller.

So I’ve used this method from Css-tricks.

In the css do this:

.aspect-ratio-box::before { 
   content: ""; 
   width: 1px; 
   margin-left: -1px; 
   float: left; 
   height: 0; 
   padding-top: 56%; 
} 

.aspect-ratio-box::after { 
   /* to clear float */ 
   content: ""; 
   display: table; 
   clear: both; 
}

This uses pseudo-elements (so there’s no html bloat) to create a tiny element that will increase the height of the box, maintaining it’s aspect ratio, but the content isn’t absolutely positioned so will affect the height if there’s enough of it to fill the box.

I’ve put an example of this on Codepen which you can see here.