Use CSS Variables to Maintain the Aspect Ratio for an Element

Jhey Tompkins
InstructorJhey Tompkins
Share this video with your friends

Social Share Links

Send Tweet

In this lesson, we look at how you can use CSS variables with the calc function to maintain and configure the desired aspect ratio for elements.

Jhey Tompkins: [0:00] We want to maintain a consistent aspect ratio with these images. Currently, they have no explicit sizing and use their intrinsic sizes.

[0:07] Let's start by defining a desired height for the images. Let's go with 200px. We apply that for the height property. We can see now our images are ruled 200px too.

[0:18] Next, let's define an aspect-ratio variable. Let's start with the common 16/9. We can represent this with calc( 16 / 9). To calculate the width, we can use calc(var(--height) * var(--aspect-ratio)). The last thing to do is apply the width.

[0:39] Now all of our images have a 16/9 aspect ratio. We can update that aspect-ratio variable to play with different aspect ratios. For example, 4/3, or even 1/1, or maybe we experiment with different desired heights.

[0:56] We could even use a responsive unit like vmin. That means our elements will responsively scale with the viewport but maintain their defined aspect ratio.

[1:05] In review, we can use CSS variables to maintain an aspect ratio for our elements by using the calc function to represent an aspect ratio, defining a desired height for our element, and then using calc again to multiply that by our aspect ratio.