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.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!