Movatterモバイル変換


[0]ホーム

URL:


Do you want to master CSS layouts? I'm building a new course.Learn more

Ahmad Shadeed,

Design Engineer

Proportional Resizing with CSS Variables

Aug 28, 2020

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:

Different Width and Height Values

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 writing an ebook

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.

Enjoyed the read? If you'd like to support my work, consider buying me a coffee. Each article takes about 10 cups to create. Thanks a latte!

Support me on Ko-fi

Join my mailing list

Join over3400+ subscribers to explore my thoughts and favorite links from around the web.

I will share content that:

  • Clear and explain the point without too much words.
  • Contains at least one figure or clear example.
  • Make you learn something new, or at least to remind you of it.

Rest assure that you will receive top notch quality content recommendations.


[8]ページ先頭

©2009-2025 Movatter.jp