Fixed aspect ratio for HTML elements

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


Let us take the everyday example of square article images, the graphics of which are not necessarily square, but we would like to display them with the aspect ratio 1: 1 without additional effort and above all without distortion, whereby their width (and thus also height) change responsively should. With the following code it is very easy to do this without additional markup with the help of CSS:

1bc3a80de3db90cdf0535541236d95f2

with the result

 

But why does it work and how can other aspect ratios be created? The key to this lies in the padding property, which - given in percentage values ​​- is always based on the same basic value as the Width property (namely the width of the parent element). With padding-left and padding-right this is obvious, with padding-top and padding-bottom surprising, 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