I know this is something Chris has wanted forever, so it’s no surprise he’s already got a fantastic write-up just a day after the news broke. In fact, I first learned about it from his post and was unable to dredge up any sort of announcement. So, I thought I’d jot some notes down because it feels like a significant development.
The news: transitioning to auto is now a thing! Well, it’s going to be a thing. Chrome Canary recently shipped support for it and that’s the only place you’ll find it for now. And even then, we just don’t know if the Chrome Canary implementation will find its way to the syntax when the feature becomes official.
The problem
Here’s the situation. You have an element. You’ve marked it up, plopped in contents, and applied a bunch of styles to it. Do you know how tall it is? Of course not! Sure, we can ask JavaScript to evaluate the element for us, but as far as CSS is concerned, the element’s computed dimensions are unknown.
That makes it difficult to, say, animate that element from height: 0 to height: whatever. We need to know what “whatever” is and we can only do that by setting a fixed height on the element. That way, we have numbers to transition from zero height to that specific height.
But what happens if that element changes over time? Maybe the font changes, we add padding, more content is inserted… anything that changes the dimensions. We likely need to update that height: 300px to whatever new fixed height works best. This is why we often see JavaScript used to toggle things that expand and contract in size, among other workarounds.
I say this is about the height property, but we’re also talking about the logical equivalent, block-size, as well as width and inline-size. Or any direction for that matter!
Transitioning to auto
That’s the goal, right? We tend to reach for height: auto when the height dimension is unknown. From there, we let JavaScript calculate what that evaluates to and take things from there.
The current Chrome implementation uses CSS calc() to do the heavy lifting. It recognizes the auto keyword and, true to its name, calculates that number. In other words, we can do this instead of the fixed-height approach:
That’s really it! Of course, calc() is capable of more complex expressions but the fact that we can supply it with just a vague keyword about an element’s height is darn impressive. It’s what allows us to go from a fixed value to the element’s intrinsic size and back.
I had to give it a try. I’m sure there are a ton of use cases here, but I went with a floating button in a calendar component that indicates a certain number of pending calendar invites. Click the button, and a panel expands above the calendar and reveals the invites. Click it again and the panel goes back to where it came from. JavaScript is handling the click interaction, triggering a class change that transitions the height in CSS.
A video in case you don’t feel like opening Canary:
The transition property in CSS lets the browser know that we plan on changing the height property at some point, and to make it smooth. And, as with any transition or animation, it’s a good idea to account for motion sensitivities by slowing down or removing the motion with prefers-reduced-motion.
What about display: none?
This is one of the first questions that popped into my head when I read Chris’s post and he gets into that as well. Transitioning from an element from display: none to its intrinsic size is sort of like going from height: 0. It might seem like a non-displayed element has zero height, but it actually does have a computed height or auto unless a specific height is declared on it.
So, there’s extra work to do if we want to transition from display: none in CSS. I’ll simply plop in the code Chris shared because it nicely demonstrates the key parts:
The element starts with both display: none and height: 0.
There’s an .open class that sets the element’s height to calc(auto).
Those are the two dots we need to connect and we do it by first setting transition-behavior: allow-discrete on the element. This is new to me, but the spec says that transition-behavior “specifies whether transitions will be started or not for discrete properties.” And when we declare allow-discrete, “transitions will be started for discrete properties as well as interpolable properties.”
Well, DevTools showed us right there that height: auto is a discrete property! Notice the @starting-style declaration, though. If you’re unfamiliar with it, you’re not alone. The idea is that it lets us set a style for a transition to “start” with. And since our element’s discrete height is auto, we need to tell the transition to start at height: 0 instead:
There was once upon a time that we were going to get a brand-new <popover> element in HTML for this. Chromium was working on development as recently as September 2021 but reached a point where it was dropped in favor of a popover attribute instead. That seems to make the most sense given that any element can be a popover — we merely need to attach it to the attribute to enable it.
<div popover>
<!-- Stuff -->
</div>
This is interesting because let’s say we have some simple little element we’re using as a popover:
<div>👋</div>
If this is all the markup we have and we do absolutely nothing in the CSS, then the waving emoji displays as you might expect.
Add that popover attribute to the mix, however, and it’s gone!
That’s perhaps the first thing that threw me off. Most times something disappears and I assume I did something wrong. But cracking open DevTools shows this is exactly what’s supposed to happen.
The element is set to display: none by default.
There may be multiple popovers on a page and we can differentiate them with IDs.
That’s not enough, as we also need some sort of “trigger” to make the popover, well, pop! We get another attribute that turns any button (or <input>-flavored button) into that trigger.
Now we have a popover “targeted ” to a <button>. When the button is clicked, the popover element toggles visibility.
This is where stuff gets really fun because now that CSS is capable of handling logic to toggle visibility, we can focus more on what happens when the click happens.
Like, right now, the emoji is framed by a really thick black border when it is toggled on. That’s a default style.
Notice that the border sizing in the Box Model diagram.
A few other noteworthy things are going on in DevTools there besides the applied border. For example, notice that the computed width and height behave more like an inline element than a block element, even though we are working with a straight-up <div> — and that’s true even though the element is clearly computing as display: block. Instead, what we have is an element that’s sized according to its contents and it’s placed in the dead center of the page. We haven’t even added a single line of CSS yet!
Speaking of CSS, let’s go back to removing that default border. You might think it’s possible by declaring no border on the element.
/* Nope 👎 */
#wave {
border: 0;
}
There’s actually a :popover-open pseudo-class that selects the element specifically when it is in an “open” state. I’d love this to be called :popover-popped but I digress. The important thing is that :popover-open only matches the popover element when it is open, meaning these styles are applied after those declared on the element selector, thus overriding them.
Another way to do this? Select the [popover] attribute:
/* Select all popovers on the page */
[popover] {
border: 0;
}
/* Select a specific popover: */
#wave[popover] {
border: 0;
}
/* Same as: */
#wave:popover-open {
border: 0;
}
With this in mind, we can, say, attach an animation to the #wave in its open state. I’m totally taking this idea from one of Jhey’s demos.
Wait, wait, there’s more! Popovers can be a lot like a <dialog> with a ::backdrop if we need it. The ::backdrop pseudo-element can give the popover a little more attention by setting it against a special background or obscuring the elements behind it.
I love this example that Mojtaba put together for us in the Almanac, so let’s go with that.
Can you imagine all the possibilities?! Like, how much easier will it be to create tooltips now that CSS has abstracted the visibility logic? Much, much easier.
Michelle Barker notes that this is probably less of a traditional “tooltip” that toggles visibility on hover than it is a “toggletip” controlled by click. That makes a lot of sense. But the real reason I mention Michelle’s post is that she demonstrates how nicely the Popover API ought to work with CSS Anchor Positioning as it gains wider browser support. That will help clean out the magic numbers for positioning that are littering my demo.
Here’s another gem from Jhey: a popover doesn’t have to be a popover. Why not repurpose the Popover API for other UI elements that rely on toggled visibility, like a slide-out menu?
Oh gosh, look at that: it’s getting late. There’s a lot more to the Popover API that I’m still wrapping my head around, but even the little bit I’ve played with feels like it will go a long way. I’ll drop in a list of things I have bookmarked to come back to. For now, though, thanks for letting me pop back in for a moment to say hi.
Container queries are often considered a modern approach to responsive web design where traditional media queries have long been the gold standard — the reason being that we can create layouts made with elements that respond to, say, the width of their containers rather than the width of the viewport.
.parent {
container-name: hero-banner;
container-type: inline-size;
/* or container: hero-banner / inline-size; */
}
}
.child {
display: flex;
flex-direction: column;
}
/* When the container is greater than 60 characters... */
@container hero-banner (width > 60ch) {
/* Change the flex direction of the .child element. */
.child {
flex-direction: row;
}
}
Why care about CSS Container Queries?
When using a container query, we give elements the ability to change based on their container’s size, not the viewport.
They allow us to define all of the styles for a particular element in a more predictable way.
They are more reusable than media queries in that they behave the same no matter where they are used. So, if you were to create a component that includes a container query, you could easily drop it into another project and it will still behave in the same predictable fashion.
They introduce new types of CSS length units that can be used to size elements by their container’s size.
This example registers a new container named card-grid that can be queried by its inline-size, which is a fancy way of saying its “width” when we’re working in a horizontal writing mode. It’s a logical property. Otherwise, “inline” would refer to the container’s “height” in a vertical writing mode.
The container-name property is used to register an element as a container that applies styles to other elements based on the container’s size and styles.
The container-type property is used to register an element as a container that can apply styles to other elements when it meets certain conditions.
The container property is a shorthand that combines the container-name and container-type properties into a single declaration.
Some Possible Gotchas
The container-name property is optional. An unnamed container will match any container query that does not target a specific container, meaning it could match multiple conditions.
The container-type property is required if we want to query a container by its size or inline-size. The size refers to the container’s inline or block direction, whichever is larger. The inline-size refers to the container’s width in the default horizontal writing mode.
The container-type property’s default value is normal. And by “normal” that means all elements are containers by default, only they are called Style Containers and can only be queried by their applied styles. For example, we can query a container’s background-color value and apply styles to other elements when the value is a certain color value.
A container cannot change its own styles. Rather, they change the styles of their contents instead. In other words, we cannot change the container’s background-color when it is a certain size — but we can change the background-color of any element inside the container. “You cannot style what you query” is a way to think about it.
A container cannot be sized by what’s in it. Normally, an element’s contents influence its size — as in, the more content in it, the larger it will be, and vice versa. But a container must be sized explicitly as part of a flex or grid layout.
The @container at-rule property informs the browser that we are working with a container query rather than, say, a media query (i.e., @media).
The my-container part in there refers to the container’s name, as declared in the container’s container-name property.
The article element represents an item in the container, whether it’s a direct child of the container or a further ancestor. Either way, the element must be in the container and it will get styles applied to it when the queried condition is matched.
Some Possible Gotchas
The container’s name is optional. If we leave it out, then any registered container would match when the conditions are met.
A container’s width can be queried with when the container-type property is set to eithersize or inline-size. That’s because size can query the element’s width or height; meanwhile, inline-size can only refer to the width.
You can query any length. So, in addition to width (i.e., inline-size), there’s an element’s aspect-ratio, block-size (i.e., height), and orientation (e.g. portrait and landscape).
Queries support the range syntax. Most of the examples so far have shown “greater than” (>) and “less than” (<), but there is also “equals” (=) and combinations of the three, such as “more than or equal to” (>=) and “less than or equal to” (<=).
Queries can be chained. That means we can write queries that meet multiple conditions with logical keywords, like and, or, and not.
Container Queries Properties & Values
Container Queries Properties & Values
container-name
container-name: none | <custom-ident>+;
Value Descriptions
none: The element does not have a container name. This is true by default, so you will likely never use this value, as its purpose is purely to set the property’s default behavior.
<custom-ident>: This is the name of the container, which can be anything, except for words that are reserved for other functions, including default, none, at, no, and or. Note that the names are not wrapped in quotes.
Computed value:none or an ordered list of identifiers
Canonical order: Per grammar
Animation: Not animatable
container-type
container-type: normal | size | inline-size;
Value Descriptions
normal: This indicates that the element is a container that can be queried by its styles rather than size. All elements are technically containers by default, so we don’t even need to explicitly assign a container-type to define a style container.
size: This is if we want to query a container by its size, whether we’re talking about the inline or block direction.
inline-size: This allows us to query a container by its inline size, which is equivalent to width in a standard horizontal writing mode. This is perhaps the most commonly used value, as we can establish responsive designs based on element size rather than the size of the viewport as we would normally do with media queries.
If <'container-type'> is omitted, it is reset to its initial value of normalwhich defines a style container instead of a size container. In other words, all elements are style containers by default, unless we explicitly set the container-type property value to either size or inline-size which allows us to query a container’s size dimensions.
1% of the queried container’s inline size, which is its width in a horizontal writing mode.
cqb
Container query block size
1% of the queried container’s inline size, which is its height in a horizontal writing mode.
Container Minimum & Maximum Lengths
Unit
Name
Equivalent to…
cqmin
Container query minimum size
The value of cqi or cqb, whichever is smaller.
cqmax
Container query maximum size
The value of cqi or cqb, whichever is larger.
Container Style Queries
Container Style Queries is another piece of the CSS Container Queries puzzle. Instead of querying a container by its size or inline-size, we can query a container’s CSS styles. And when the container’s styles meet the queried condition, we can apply styles to other elements. This is the sort of “conditional” styling we’ve wanted on the web for a long time: If these styles match over here, then apply these other styles over there.
CSS Container Style Queries are only available as an experimental feature in modern web browsers at the time of this writing, and even then, style queries are only capable of evaluating CSS custom properties (i.e., variables).
Browser Support
The feature is still considered experimental at the time of this writing and is not supported by any browser, unless enabled through feature flags.
This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.
Desktop
Chrome
Firefox
IE
Edge
Safari
128
No
No
125
TP
Mobile / Tablet
Android Chrome
Android Firefox
Android
iOS Safari
125
No
125
No
Registering a Style Container
article {
container-name: card;
}
That’s really it! Actually, we don’t even need the container-name property unless we need to target it specifically. Otherwise, we can skip registering a container altogether.
And if you’re wondering why there’s no container-type declaration, that’s because all elements are already considered containers. It’s a lot like how all elements are position: relative by default; there’s no need to declare it. The only reason we would declare a container-type is if we want a CSS Container Size Query instead of a CSS Container Style Query.
So, really, there is no need to register a container style query because all elements are already style containers right out of the box! The only reason we’d declare container-name, then, is simply to help select a specific container by name when writing a style query.
Using a Style Container Query
@container style(--bg-color: #000) {
p { color: #fff; }
}
In this example, we’re querying any matching container (because all elements are style containers by default).
Notice how the syntax it’s a lot like a traditional media query? The biggest difference is that we are writing @container instead of @media. The other difference is that we’re calling a style() function that holds the matching style condition. This way, a style query is differentiated from a size query, although there is no corresponding size() function.
In this instance, we’re checking if a certain custom property named --bg-color is set to black (#000). If the variable’s value matches that condition, then we’re setting paragraph (p) text color to white (#fff).
Browser support for CSS Container Size Queries is great. It’s just style queries that are lacking support at the time of this writing.
Chrome 105 shipped on August 30, 2022, with support.
Safari 16 shipped on September 12, 2022, with support.
Firefox 110 shipped on February 14, 2023, with support.
This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.
Desktop
Chrome
Firefox
IE
Edge
Safari
106
110
No
106
16.0
Mobile / Tablet
Android Chrome
Android Firefox
Android
iOS Safari
125
126
125
16.0
Demos!
Card Component
In this example, a “card” component changes its layout based on the amount of available space in its container.
Call to Action Panel
This example is a lot like those little panels for signing up for an email newsletter. Notice how the layout changes three times according to how much available space is in the container. This is what makes CSS Container Queries so powerful: you can quite literally drop this panel into any project and the layout will respond as it should, as it’s based on the space it is in rather than the size of the browser’s viewport.
Stepper Component
This component displays a series of “steps” much like a timeline. In wider containers, the stepper displays steps horizontally. But if the container becomes small enough, the stepper shifts things around so that the steps are vertically stacked.
Icon Button
Sometimes we like to decorate buttons with an icon to accentuate the button’s label with a little more meaning and context. And sometimes we don’t know just how wide that button will be in any given context, which makes it tough to know when exactly to hide the icon or re-arrange the button’s styles when space becomes limited. In this example, an icon is displayed to the right edge of the button as long as there’s room to fit it beside the button label. If room runs out, the button becomes a square tile that stacks the icons above the label. Notice how the border-radius is set in container query units, 4cqi, which is equal to 4% of the container’s inline-size (i.e. width) and results in rounder edges as the button grows in size.
Pagination
Pagination is a great example of a component that benefits from CSS Container Queries because, depending on the amount of space we have, we can choose to display links to individual pages, or hide them in favor of only two buttons, one to paginate to older content and one to paginate to newer content.