Fixed aspect ratio for HTML elements

As a web developer, you often find yourself in the dilemma of working with HTML elements that - unlike the img element, for example - have neither a fixed size nor a fixed aspect ratio. Often you want to ensure that these objects behave responsively, but the proportion between width and height is maintained. By default, CSS does not offer an intuitive solution here. But with the help of the vertical padding property you can achieve your goal.


Let's take the everyday example of square product images. While the graphics themselves aren't necessarily square, we'd like to display them with a 1:1 aspect ratio without any extra effort or distortion, and their width (and therefore height) should change responsively. The following code makes it easy to achieve this using CSS without any additional markup.:

1bc3a80de3db90cdf0535541236d95f2

with the result:

 

But why does this work and how can other aspect ratios be created? The key to this lies in the padding property, which - specified in percentage values ​​- is always based on the same basic value as the Width property (namely the width of the parent element). This is obvious for padding-left and padding-right, surprising for padding-top and padding-bottom, but very helpful in this case.

For example, if you want an aspect ratio of 16:9, you could choose the values width:100%;padding-bottom:56.25%;. An aspect ratio that takes into account the golden ratio can be realized with the values width:100%;padding-bottom:61.81%;.

With the help of calc you can directly specify the aspect ratio, for example for 16:9 with padding-bottom:calc(1 / (16 / 9) * 100%) If the element consists of further nested elements, position the child element absolutely to compensate the padding of the parent element:

1bc3a80de3db90cdf0535541236d95f2

This leads to the following result:

...
Back