We’ve relied on media queries for a in point of fact prolonged time within the responsive world of CSS however they’ve their share of limitations and web shifted focal point extra in direction of accessibility than responsiveness alone. Here is the attach CSS Container Queries reach in. They fully change how we capability responsiveness, shifting the paradigm away from a viewport-primarily primarily primarily based mentality to one which is extra thoughtful of a ingredient’s context, a lot like its size or inline-size.
Querying parts by their dimensions is without doubt one of the essential 2 things that CSS Container Queries can pause, and, if truth be told, we name these container size queries to assist distinguish them from their ability to query in opposition to a ingredient’s recent styles. We name these container style queries.
Contemporary container query protection has been largely inquisitive about container size queries, which revel in 90% global browser toughen at the time of this writing. Vogue queries, on the a ramification of hand, are only accessible within the good thing about a characteristic flag in Chrome 111+ and Safari Technology Preview.
The necessary query that involves mind is What are these style query things? followed straight by How pause they work?. There are some nice primers on them that others web written, and they also are rate sorting out.
But the extra intelligent query about CSS Container Vogue Queries would possibly in actuality be Why we ought to gathered narrate them? The answer, as repeatedly, is nuanced and would possibly simply be it depends upon. But I should lunge at style queries a minute bit extra deeply, not at the syntax stage, however what exactly they are solving and what variety of narrate cases we would get ourselves reaching for them in our work if and when they place browser toughen.
Talking purely about responsive originate, media queries web simply fallen short in some aspects, however I ponder the necessary one is that they are context-agnostic within the sense that they simply be aware of the viewport size when making narrate of styles without intelligent the scale or dimensions of a fraction’s mother or father or the express material it contains.
This on the total isn’t an plight since we only web a predominant component that doesn’t share condominium with others alongside the x-axis, so we can style our express material looking on the viewport’s dimensions. Nevertheless, if we stuff a fraction into a smaller mother or father and retain the identical viewport, the media query doesn’t kick in when the express material turns into diminutive. This forces us to jot down and handle a total location of media queries that target natty-explicit express material breakpoints.
Container queries rupture this limitation and permit us to query noteworthy extra than the viewport’s dimensions.

How Container Queries In total Work
Container size queries work equally to media queries however allow us to web a look at styles looking on the container’s properties and computed values. In short, they enable us to kind style modifications in step with a fraction’s computed width or height in spite of the viewport. This variety of bid turned into once only seemingly with JavaScript or the ol’ jQuery, as this situation reveals.
As infamous earlier, though, container queries can query a fraction’s styles moreover to its dimensions. In a ramification of words, container style queries can stare at and music a fraction’s properties and observe styles to a ramification of parts when those properties meet move conditions, a lot like when the component’s background-color is location to hsl(0 50% 50%).
That’s what we point out when talking about CSS Container Vogue Queries. It’s a proposed characteristic outlined within the identical CSS Containment Module Level 3 specification as CSS Container Dimension Queries — and one which’s at this time unsupported by any predominant browser — so the adaptation between style and size queries can web a minute bit confusing as we’re technically talking about two associated components below the identical umbrella.
We’d pause ourselves a favor to trail into reverse and first perceive what a “container” is within the necessary attach of abode.
Containers
A part’s container is any ancestor with a containment context; it goes to be the component’s bellow mother or father or presumably a grandparent or sizable-grandparent.
A containment context scheme that a vivid component would possibly maybe also be celebrated as a container for querying. Unofficially, you presumably can negate there are two kinds of containment context: size containment and style containment.
Dimension containment scheme we can query and music a fraction’s dimensions (i.e., aspect-ratio, block-size, height, inline-size, orientation, and width) with container size queries as prolonged as it’s registered as a container. Tracking a fraction’s dimensions requires a minute bit processing within the shopper. One or two parts are a scuttle, however if we needed to constantly music the size of all parts — including resizing, scrolling, animations, and so on — it will likely be a huge efficiency hit. That’s why no component has size containment by default, and now we web to manually register a size query with the CSS container-type property when we need it.
On the a ramification of hand, style containment lets us query and music the computed values of a container’s explicit properties via container style queries. As it at this time stands, we can only check for personalized properties, e.g. --theme: dark, however rapidly lets check for a fraction’s computed background-color and display property values. Unlike size containment, we are checking for uncooked style properties before they are processed by the browser, alleviating efficiency and allowing all parts to web style containment by default.
Did you salvage that? Whereas size containment is something we manually register on a fraction, style containment is the default habits of all parts. There’s no web to register a style container because all parts are style containers by default.
And how can we register a containment context? The finest capability is to narrate the container-type property. The container-type property will give a fraction a containment context and its three authorized values — normal, size, and inline-size — elaborate which properties we can query from the container.
/* Size containment in the inline direction */
.parent {
container-type: inline-size;
}
This instance formally establishes a size containment. If we had performed nothing in any respect, the .parent component is already a container with a style containment.
Dimension Containment
That final example illustrates size containment in step with the component’s inline-size, which is a adore job of announcing its width. Once we focus on about identical outdated doc plod on the fetch, we’re talking about parts that plod in an inline direction and a block direction that corresponds to width and height, respectively, in a horizontal writing mode. If we had been to rotate the writing mode in recount that it is vertical, then “inline” would consult with the height as a change and “block” to the width.
Rob into legend the next HTML:
We would possibly give the .cards-container component a containment context within the inline direction, allowing us to kind modifications to its descendants when its width turns into too minute to effectively demonstrate all the pieces within the recent structure. We encourage the identical syntax as in a identical outdated media query however swap @media for @container
.cards-container {
container-type: inline-size;
}
@container (width < 700px) {
.cards {
background-color: red;
}
}
Container syntax works nearly the identical as media queries, so we can narrate the and, or, and not operators to chain a ramification of queries collectively to match a pair of conditions.
@container (width < 700px) or (width > 1200px) {
.cards {
background-color: red;
}
}
Aspects in a size query stare the closest ancestor with size containment so we can observe modifications to parts deeper within the DOM, like the .card component in our earlier example. If there would possibly be never this sort of thing as a size containment context, then the @container at-rule won’t web any pause.
/* 👎
* Apply styles based on the closest container, .cards-container
*/
@container (width < 700px) {
.card {
background-color: black;
}
}
Right making an strive to get the closest container is messy, so it’s appropriate practice to title containers utilizing the container-name property after which specifying which container we’re monitoring within the container query appropriate after the @container at-rule.
.cards-container {
container-name: cardsContainer;
container-type: inline-size;
}
@container cardsContainer (width < 700px) {
.card {
background-color: #000;
}
}
We are in a position to narrate the shorthand container property to location the container title and kind in a single declaration:
.cards-container {
container: cardsContainer / inline-size;
/* Equivalent to: */
container-name: cardsContainer;
container-type: inline-size;
}
The a ramification of container-type we can location is size, which works exactly like inline-size — only the containment context is both the inline and block instructions. That scheme we would possibly furthermore furthermore query the container’s height sizing moreover to its width sizing.
/* When container is less than 700px wide */
@container (width < 700px) {
.card {
background-color: black;
}
}
/* When container is less than 900px tall */
@container (height < 900px) {
.card {
background-color: white;
}
}
And it’s rate noting right here that if two separate (not chained) container principles match, the most explicit selector wins, lawful to how the CSS Cascade works.
As a lot as now, we’ve touched on the notion that of CSS Container Queries at its most basic. We elaborate the variety of containment we need on a fraction (we regarded namely at size containment) after which query that container accordingly.
Container Vogue Queries
The third cost that is authorized by the container-type property is normal, and it sets style containment on a fraction. Both inline-size and size are web sooner or later of all predominant browsers, however normal is more moderen and only has modest toughen at the 2nd.
I be aware of normal a minute little bit of an oddball because we don’t web to explicitly utter it on a fraction since all parts are style containers with style containment lawful out of the field. It’s seemingly you’ll never write it out your self or stare it within the wild.
.parent {
/* Unnecessary */
container-type: normal;
}
Within the event you pause write it or stare it, it’s likely to undo size containment declared in other locations. But even then, it’s seemingly to reset containment with the worldwide initial or revert key phrases.
.parent {
/* All of these (re)set style containment */
container-type: normal;
container-type: initial;
container-type: revert;
}
Let’s stare at a straightforward and a minute contrived example to web the purpose sooner or later of. We are in a position to elaborate a personalised property in a container, negate a --theme.
.cards-container {
--theme: dark;
}
From right here, we can check if the container has that desired property and, if it does, observe styles to its descendant parts. We are in a position to’t straight style the container since it can maybe unleash an infinite loop of altering the styles and querying the styles.
.cards-container {
--theme: dark;
}
@container style(--theme: dark) {
.cards {
background-color: black;
}
}
Leer that style() characteristic? In due direction, lets should check if a fraction has a max-width: 400px via a style query rather then checking if the component’s computed cost is bigger than 400px in a size query. That’s why we narrate the style() wrapper to utter apart style queries from size queries.
/* Size query */
@container (width > 60ch) {
.cards {
flex-direction: column;
}
}
/* Style query */
@container style(--theme: dark) {
.cards {
background-color: black;
}
}
Both kinds of container queries stare the closest ancestor with a corresponding containment-type. In a style() query, it goes to repeatedly be the mummy or father since all parts web style containment by default. On this case, the bellow mother or father of the .cards component in our ongoing example is the .cards-container component. If we should query non-bellow of us, we can need the container-name property to utter apart between containers when making a question.
.cards-container {
container-name: cardsContainer;
--theme: dark;
}
@container cardsContainer style(--theme: dark) {
.card {
color: white;
}
}
Unfamiliar and Confusing Things About Container Vogue Queries
Vogue queries are fully new and bring something never considered in CSS, in recount that they are move to web some confusing qualities as we wrap our heads around them — some which would possibly be fully intentional and well notion-out and a few which would possibly be presumably unintentional and would possibly be as a lot as this point in future variations of the specification.
Vogue and Dimension Containment Aren’t Mutually Distinctive
One intentional perk, as an instance, is that a container can web both size and style containment. No person would fault you for wanting forward to that size and style containment are mutually bizarre considerations, so atmosphere a fraction to something like container-type: inline-size would kind all style queries ineffective.
Nevertheless, one other comical bid about container queries is that parts web style containment by default, and there isn’t in actuality a capability to put off it. Take a look at out this subsequent example:
.cards-container {
container-type: inline-size;
--theme: dark;
}
@container style(--theme: dark) {
.card {
background-color: black;
}
}
@container (width < 700px) {
.card {
background-color: red;
}
}
Leer that? We are in a position to gathered query the parts by style even when we explicitly location the container-type to inline-size. This looks contradictory initially, however it does kind sense, brooding about that style and size queries are computed independently. It’s better this suggests since both queries don’t necessarily battle with each a ramification of; a style query would possibly change the colours in a fraction looking on a personalised property, while a container query modifications a fraction’s flex-direction when it gets too minute for its contents.
Leer the Pen [Conflicting Style and Size Queries [forked]](https://codepen.io/smashingmag/pen/KKLyeQQ) by Monknow.
If active style and size queries are configured to web a look at conflicting styles, the most explicit selector wins in step with the cascade, so the parts web a dark background shade till the container gets below 700px and the scale query (which is written with extra specificity in this situation than the final one) kicks in.
Unnamed Vogue Queries Take a look at Every Ancestor For a Match
In that final example, that you would possibly presumably furthermore neutral web noticed one other extraordinary bid in style queries: The .card component is inner an unnamed style query, so since all parts web a style containment, it will gathered be querying its mother or father, .cards. Nevertheless, the .cards component doesn’t web any longer or less --theme property; it’s the .cards-container component that does, however the style query is active!
.cards-container {
--theme: dark;
}
@container style(--theme: dark) {
/* This is still active! */
.card {
background-color: black;
}
}
How does this happen? Don’t unnamed style queries query only their mother or father component? Neatly, not exactly. If the mummy or father doesn’t web the personalized property, then the unnamed style query looks for ancestors bigger up the chain. If we add a --theme property on the mummy or father with one other cost, you would possibly maybe stare the style query will narrate that component because the container, and the query now not matches.
.cards-container {
--theme: dark;
}
.cards {
--theme: light; /* This is now the matching container for the query */
}
/* This query is no longer active! */
@container style(--theme: dark) {
.card {
background-color: black;
}
}
I don’t perceive how intentional this habits is, however it reveals how messy things can web when working with unnamed containers.
Aspects Are Vogue Containers By Default, But Styles Queries Are No longer
The real fact that style queries are the default container-type and size is the default query looks a minute bit mismatched in that now we web to explicitly utter a style() characteristic to jot down the default variety of query while there would possibly be never this sort of thing as a corresponding size() characteristic. This isn’t a knock on the specification, however loads of things in CSS you appropriate web to handle in mind.
What Are Container Vogue Queries Right For?
At the beginning stare, style queries appear like a characteristic that opens up endless potentialities. But after playing with them, you don’t in actuality web a transparent notion of what grief they’d solve — not not as a lot as not after the time I’ve spent with them. The total narrate cases I’ve considered or notion up aren’t straight all that worthwhile, and the most perfect ones solve complications with well-established solutions already in attach of abode. A brand new job of writing CSS in step with styles reacting to a ramification of styles looks releasing (the extra ways to jot down CSS, the merrier!), however if we’re already having effort most regularly naming things, imagine how not easy managing and asserting those states and styles would possibly maybe also be.
I know all these are mettlesome statements, however they aren’t counterfeit, so let me unpack them.
The Most Apparent Use Case
As we’ve mentioned, we can only query personalized properties with style queries at the 2nd, so the clearest narrate for them is storing bits of divulge that will per chance also be celebrated to change UI styles when they change.
Let’s negate now we web a web app, presumably a sport featuring a global leaderboard of top avid gamers. Every merchandise within the leaderboard is a ingredient in step with a participant that wants a ramification of styling looking on that participant’s attach of abode on the leaderboard. We would possibly style the necessary-attach of abode participant with a gold background, the 2nd-attach of abode participant with silver, and the third-attach of abode with bronze, while the final avid gamers are all styled with the identical background shade.
Let’s also judge that this just is not a static leaderboard. Gamers change locations as their scores change. That scheme we’re presumably serving the utilizing a server-side rendering (SSR) framework to retain the leaderboard as a lot as date with the most in style files, so lets insert that files into the UI via inline styles with each attach of abode as a personalised property, --position: number.
Here’s how lets structure the markup:
-
Roi
Now, we can narrate style queries to check the recent merchandise’s attach of abode and observe their respective sparkling backgrounds to the leaderboard.
.item-container {
container-name: leaderboard;
/* No need to apply container-type: normal */
}
@container leaderboard style(--position: 1) {
.item {
background: linear-gradient(45deg, yellow, orange); /* gold */
}
}
@container leaderboard style(--position: 2) {
.item {
background: linear-gradient(45deg, grey, white); /* silver */
}
}
@container leaderboard style(--position: 3) {
.item {
background: linear-gradient(45deg, brown, peru); /* bronze */
}
}
Leer the Pen[VogueQueriesUseCase[StyleQueriesUseCase[forked]](https://codepen.io/smashingmag/pen/vYwWrRL) by Monknow.
Some browser purchasers don’t completely toughen style queries from an embedded CodePen, however it will gathered work ought to you completely open the demo in one other tab. Despite all the pieces, right here is a screenshot of the scheme in which it looks appropriate in case.

But We Can Have the Identical Aspect With CSS Classes and IDs
Most container query guides and tutorials I’ve considered narrate identical examples to illustrate the basic notion, however I will’t pause pondering in spite of how chilly style queries are, we can lift out the identical end result utilizing classes or IDs and with less boilerplate. As an different of passing the divulge as an inline style, lets simply add it as a category.
-
Roi
Alternatively, lets add the attach of abode number straight inner an id so we don’t web to transform the number into a string:
-
Roi
Both of those approaches trail away us with cleaner HTML than the container queries capability. With style queries, now we web to wrap our parts inner a container — even supposing we don’t semantically need it — because of the reality that containers (rightly) are unable to style themselves.
We even web less boilerplate-y code on the CSS side:
#item-1 {
background: linear-gradient(45deg, yellow, orange);
}
#item-2 {
background: linear-gradient(45deg, grey, white);
}
#item-3 {
background: linear-gradient(45deg, brown, peru);
}
Leer the Pen[VogueQueriesUseCaseChangedwithClasses[StyleQueriesUseCaseReplacedwithClasses[forked]](https://codepen.io/smashingmag/pen/oNRoydN) by Monknow.
As an apart, I know that utilizing IDs as styling hooks is in total considered as a no-no, however that’s only because IDs ought to be uncommon within the sense that no two circumstances of the identical ID are on the page at the identical time. On this instance, there would possibly furthermore neutral not ever be a pair of first-attach of abode, 2nd-attach of abode, or third-attach of abode participant on the page, making IDs a web and appropriate different in this plight. But, sure, lets also narrate some a ramification of variety of selector, negate a data-* attribute.
There is something that would possibly add loads of cost to style queries: a unfold syntax for querying styles. Here is an open characteristic that Miriam Suzanne proposed in 2023, the root being that it queries numerical values utilizing vary comparisons appropriate like size queries.
Factor in if we desired to web a look at a gradual crimson background shade to the remainder of the pinnacle ten avid gamers within the leaderboard example. As an different of adding a question for every attach of abode from four to 10, lets add a question that tests a unfold of values. The syntax is obviously not within the spec at the present, however let’s negate it looks something like this appropriate to push the purpose sooner or later of:
/* Do not try this at home! */
@container leaderboard style(4 >= --position <= 10) {
.item {
background: linear-gradient(45deg, purple, fuchsia);
}
}
On this fictional and hypothetical example, we’re:
- Tracking a container called
leaderboard, - Making a
style()query in opposition to the container, - Evaluating the
--positionpersonalized property, - Procuring for a condition the attach the personalized property is location to a designate equal to a number that is bigger than or equal to
4and not as a lot as or equal to10. - If the personalized property is a value within that adjust, we location a participant’s background shade to a
linear-gradient()that goes frompurpletofuschia.
Here is very chilly, however if this extra or less habits is probably going to be performed utilizing parts in in style frameworks, like React or Vue, lets also location up a unfold in JavaScript and toggle on a .top-ten class when the condition is met.
Leer the Pen[VogueRangedQueriesUseCaseChangedwithClasses[StyleRangedQueriesUseCaseReplacedwithClasses[forked]](https://codepen.io/smashingmag/pen/OJYOEZp) by Monknow.
Definite, it’s sizable to stare that we can pause this variety of bid straight in CSS, however it’s also something with an existing well-established resolution.
Keeping apart Vogue Logic From Logic Logic
As a lot as now, style queries don’t seem like the glorious resolution for the leaderboard narrate case we checked out, however I wouldn’t judge them ineffective exclusively because we can lift out the identical bid with JavaScript. I'm a substantial advocate of reaching for JavaScript only when essential and only in sprinkles, however style queries, the ones the attach we can only check for personalized properties, are presumably to be worthwhile when paired with a UI framework the attach we can without complications reach for JavaScript within a ingredient. I even web been utilizing Astro an awful lot as we remark, and in that context, I don’t stare why I'd settle a style query over programmatically altering a category or ID.
Nevertheless, a case would possibly maybe also be made that enforcing style good judgment inner a ingredient is messy. Maybe we ought to gathered encourage the good judgment referring to styles within the CSS away from the remainder of the good judgment good judgment, i.e., the stateful modifications inner a ingredient like conditional rendering or capabilities like useState and useEffect in React. The style good judgment would possibly be the conditional tests we pause so that you would possibly add or put off class names or IDs so that you would possibly change styles.
If we trail into reverse to our leaderboard example, checking a participant’s attach of abode to web a look at a ramification of styles would possibly be style good judgment. We would possibly certainly check that a participant’s leaderboard attach of abode is between four and ten utilizing JavaScript to programmatically add a .top-ten class, however it will point out leaking our style good judgment into our ingredient. In React (for familiarity, however it will likely be a lot like a ramification of frameworks), the ingredient would possibly furthermore neutral stare like this:
const LeaderboardItem = ({attach of abode}) => {
= 4 && attach of abode <= 10 ? "top-ten" : ""}`} id={`item-${position}`}>
Roi
;
};
Besides this being monstrous-wanting code, adding the style good judgment in JSX can web messy. Within the interim, style queries can plod the --position cost to the styles and handle the good judgment straight within the CSS the attach it is being celebrated.
const LeaderboardItem = ({attach of abode}) => {
Roi
;
};
Out of the ordinary cleaner, and I ponder this is nearer to the associated rate proposition of style queries. But at the identical time, this situation makes a natty leap of assumption that we will web a unfold syntax for style queries sooner or later, which just is not a performed deal.
Conclusion
There are hundreds groups working on making in style CSS better, and not all components web to be groundbreaking miraculous additions.
It simply doesn’t solve any explicit plight or is extra healthy sufficient to change a ramification of approaches, not not as a lot as as a long way as I'm aware.
Although, in due direction, style queries can be ready to check for any property, that introduces a total new can of worms the attach styles are in a position to reacting to a ramification of styles. This looks thrilling initially, however I will’t shake the sensation it will likely be pointless and even chaotic: styles reacting to styles, reacting to styles, and so on with an pointless side of boilerplate. I’d argue that a extra prudent capability is to jot down all of your styles declaratively collectively in one attach of abode.
Maybe it will likely be worthwhile for web extensions (like Darkish Reader) to allow them to better check styles in third-occasion websites? I will’t clearly stare it. Within the event you web gotten any strategies on how CSS Container Vogue Queries would possibly maybe also be celebrated to jot down better CSS that I would possibly furthermore neutral web misplaced sight of, please let me know within the comments! I’d adore to perceive how you’re gripping about them and the sorts of ways you imagine your self utilizing them on your work.
(gg, yk)