Do you want to master CSS layouts? I'm building a new course.Learn more
For this snippet, I want to share with you something I do while resizing elements in the browser DevTools.
Let’s suppose that you’re implementing a design in HTML & CSS, and you want to experiment with an icon’s width and height. Consider the following:
.icon{--size: 32px;width:var(--size);height:var(--size);}
In the browser DevTools, you can change the--size
variable value, and bothwidth
andheight
will be affected. See the mockup below for a visual comparison betweenCSS andSketch app.
In Sketch, you need to activatelock to maintain the same value for bothwidth
and height. Here is how resizing works in the Devtools:
Not all shapes are perfect squares, what if you want to resize an element with different values forwidth
andheight
? Well, aspect ratio to the rescue.
First, you need to calculate the aspect ratio between the width and height of the element.
In this example, we have a rectangle. It’s width is186px
and the height is79px
. The goal is to calculate the ratio between those two values.
Aspect ratio = width / height
Aspect ratio = 186 / 79 = 2.35
Then, we will substitute the ration with the help of CSS calc() function.
.rect{--size: 186px;/* [1] */--aspect-ratio: 2.35;/* [2] */width:var(--size);/* [3] */height:calc(var(--size) /var(--aspect-ratio));/* [4] */}
If you want to play with the above in the browser, here is ademo on CodePen.
I’m excited to let you know that I’m writing an ebook about Debugging CSS.
If you’re interested, head over todebuggingcss.com and subscribe for updates about the book.
Join over3400+ subscribers to explore my thoughts and favorite links from around the web.
I will share content that:
Rest assure that you will receive top notch quality content recommendations.