Aspect-ratio and container query units six years later
March 16, 2023
Six years ago, I tweeted the following:
Wish there was a way to set height of element in proportion to width in CSS. So if I wanted a square, I could set height to 100% of width.
Today, I have a way to do that with aspect-ratio
. I could set aspect-ratio: 1
to achieve a square with an element.
Later in the thread, I mentioned it would be nice to have something like viewport units ( vw
or vh
) for elements. Today, we have container queries along with container units (cqw
or cqh
).
The context of my tweet was that I was playing around with CSS grid layout and flexbox. I was inspired by the menu page on the Sonic site and built a Codepen refactoring several of the page layouts using flexbox and grid.
See the Pen Sonic Menu Page with Flexbox and CSS Grid by Jeff Bridgforth (@webcraftsman) on CodePen.
I wanted to make the menu items squares like they were on the Sonic size but without having to have images to make the layout work. I ended up using a calc()
function to set a min-height on the list items for once the viewport width was 768 pixels.
.menu-item-listing li {
min-height: calc(90vw / 4);
}
That experiment launched me into learning about element or container queries. Tommy Hodgins told me about his project, EQCSS. You can read more of the story in my Container Queries article from last April.