fluid boxes with fixed aspect ratio

In some cases e.g. for displaying a responsive video we need a solution for flexible elements which keep their aspect ratio when resized. You can do this with javascript but then you are doing something wrong.

Displaying flexible images is not a problem as we might know but keeping the aspect ratio on block elements like div isn’t that easy because their height is depending on their content (height: auto) or fixed values.

When we take a deeper look into the CSS specification we see that the padding-top when given in percentage on a block is calculated out of the width of the containing element.

“Percentages: refer to the width of the containing block”


With this knowledge we are now able to produce a flexible container that keeps its aspect ratio while resizing. Lets first make a responsive video:

See the Pen responsive video – keep aspect ratio by Christoph Reinartz (@creinartz) on CodePen.0

The trick is we set the padding-top of the outer element top to 56,25% (9/16 = 56,25%) and set the parent element to position absolute and fluid 100% width and height. For a 4:3 video we would use 75% (3/4 = 75%) to have another aspect ratio.

Doing this let us solve a problem with may arise during developing a responsive website. A flexible box which should keep its aspect ratio, e.g. a box which always has the same height as its width.

Lets do this 100% x 100% box and 200% x 100%.

See the Pen Flexible box same height as width by Christoph Reinartz (@creinartz) on CodePen.0

i like this!