DEV Community

Robert Rees
Robert Rees

Posted on

CSS 2021 top tip: Aspect Ratio

Aspect Ratio completely solves a variety of historical problems in a neat and elegant way. Have you ever wanted an image to take as much horizontal space as it can while having a fixed height? Or battled with consistent sizing with a marketing department?

Aspect ratio is the answer. This surprisingly elegant attribute allows you to define a ratio of width to height which then interacts with the definitions of height and width you give the element.

So if you want full width on an image you can apply width: 100% but then leave the height on auto and let it be calculated based on the actual width to occupy the appropriate height.

You can also use it as scaling element in responsive designs as you can centre an element, set a max height and then let the layout engine calculate both dimensions to fit the ideal ratio you're looking for.

As the ratio is expressed in "natural" terms it can also be discussed directly with non-technical design people and can be used to embed style guide rules directly into your layout, making collaboration much easier.

Here's a set of illustrative demos and one demonstrating responsive qualities of positioning.

Top comments (0)