Technology

Maintaining aspect ratio in empty containers

Posted by Pixafy Team

aspect-ratio-edit

With the growing popularity of responsive web design, keeping your design fluid can be tricky when using pixel values for heights, especially when using an empty div. Why would you have empty divs, you ask? Perhaps you need background images, spacers, elements that might contain information later on with the use of JavaScript. Whatever the case may be, making sure that it scales appropriately when developing for responsive is crucial. The trick to this is the padding-bottom percentage.

When using percentage values on padding, the percentage comes from the width of the containing element. This is true even when using a percentage for padding-bottom on an element with no height. With this knowledge and the formula for aspect ratio, you’ll be able to make sure that even when using an empty div, your height will maintain a smooth transition as screen sizes change. This formula is x1 / y1 * y2 = x2 which basically states, original height divided by original width multiplied by the new desired width will give you the new desired height.

Using the popular widescreen aspect ratio of 16:9, if our screen size was 1200 wide, our height would be 675px. But we don’t want to use pixels. Instead, we want to use percentages. So if we set our containing div to 1200px and our child div to 100%, the padding-bottom of that child element would have to be set to 56.25% to maintain that same aspect ratio.

Formula:

9 / 16 * 1200(px) = 675(px)

9 / 16 * 100(%) = 56.25(%)

HTML:

<div style=”max-width=1200px;”>

<div style=”width:100%; padding-bottom:56.25%;”></div>

</div>

As you can see above, our containing element’s max-width is 1200px (max-width to allow for responsiveness). The padding-bottom in its child element is set to 56.25% to maintain a 16:9 aspect ratio when scaling.

Now, using this padding-bottom trick with background-size: cover (CSS3), you’ll be able to scale the div as well as the image when it comes to smaller devices.

Stay tuned for more handy tips and tricks!

[series_block]

Related posts:

[/series_block]

Questions or comments? Share them below, or tweet us @Pixafy!