Nesting in CSS by kirupa (https://www.kirupa.com/me/index.htm) | filed under HTML and CSS (https://www.kirupa.com/html5/learn_html_css.htm) TL;DR: CSS nesting lets us write style rules inside other style rules, the way Sass does, with no build step. A nested .title inside .card means .card .title, and the & stands in for the parent selector, so &:hover means .card:hover. We can nest media and container queries too. - Every nested rule turns into an ordinary selector we could have typed by hand, so nesting is really about keeping a component's styles together. - A space after the & matters: &.featured is the card itself, while & .featured is something inside the card. - @media and @container blocks can sit inside a rule, and their declarations apply to the parent selector. - Unlike Sass, &__title can't build class names, and nesting under a selector list scores specificity like :is(). When we style a component in CSS, we end up typing its name over and over again. There's .card, then .card .title, then .card:hover, then .card.featured .badge, and so on. All of those rules are about the same card, but they are scattered around as separate rules that only look related because they happen to start with the same word. For years, the fix was to use a preprocessor like Sass, which let us write rules inside other rules and then turned them back into regular CSS. Today, browsers understand that style of writing on their own. Here is a recipe card whose every style lives inside a single CSS rule: Live demo: A Fluffy Pancakes recipe card. Hovering lifts it with a blue border, the Featured checkbox turns it red with a Featured badge, and the Card width slider stacks its layout when it gets narrow (https://www.kirupa.com/html5/examples/css_nesting_card.htm) Try it: 1. Hover over the card 2. Check Featured 3. Drag the Card width slider all the way to the left The hover effect, the featured look, and the narrow layout all come from rules tucked inside the card's rule, and there's no build step anywhere. In the following sections, we'll take that card apart and see how all of it works. Onwards! How Does CSS Nesting Work? Let's start with how we would have styled a smaller version of our card the traditional way. We have the card, the title inside it, and a hover state: .card { padding: 18px; } .card .title { font-size: 22px; } .card:hover { border-color: #0798ff; } There's nothing wrong with this. The only annoyance is that .card shows up three times, and nothing stops a fourth .card rule from ending up 200 lines further down the file, far away from its friends. What if we could write the title's rule and the hover rule inside the card's rule? That is exactly what CSS lets us do now. Putting one style rule inside another is known as nesting, and here is our card written that way: .card { padding: 18px; .title { font-size: 22px; } &:hover { border-color: #0798ff; } } The browser reads this as the same three rules we had before. When it sees a rule nested inside .card, it treats that nested rule as being relative to the card: [Image: On the left, labeled What we write: one .card rule with padding 18px, a nested .title rule with font-size 22px, and a nested &:hover rule with border-color #0798ff. On the right, labeled What it means: three flat rules, .card with padding 18px, .card .title with font-size 22px, and .card:hover with border-color #0798ff. Arrows connect each nested rule to the flat rule it becomes.] (https://www.kirupa.com/html5/images/nest_flatten.png) The blue lines show the nested .title rule turning into .card .title. Because we wrote nothing between the card and the title, the browser assumes we mean "a .title somewhere inside the card," which is the same as putting a space between them. The yellow lines show &:hover turning into .card:hover. That ampersand is doing something a bit different, so let's look at it next. What Does the & Do? The & character is called the nesting selector, and it stands in for the parent rule's selector. Inside our .card rule, every & means .card. We need it whenever the nested selector should attach directly to the card itself rather than to something inside it, which is the case for pseudo-classes like :hover and for extra classes like .featured: .card { border: 3px solid #d9dee5; &:hover { border-color: #0798ff; } &.featured { border-color: #e0605a; background-color: #fff1ef; } } The thing to watch out for is the space after the &. A single space completely changes which element we are styling: [Image: Two nested selectors. On the left, &.featured with no space becomes .card.featured, which matches the card itself when it also has the featured class. On the right, & .featured with a space becomes .card .featured, which matches an element with the featured class somewhere inside the card.] (https://www.kirupa.com/html5/images/nest_ampersand_space.png) On the left, &.featured has no space, so it means "the card, when it also has the featured class." That's what our recipe card uses when you check the Featured box. On the right, & .featured has a space, so it means "something with the featured class inside the card." Our card doesn't have anything like that inside it, so that rule would quietly style nothing. The & doesn't have to come first, either. Putting it at the end lets a component react to where it lives on the page: .card { background-color: #ffffff; .dark-theme & { background-color: #1e2933; } } This nested rule turns into .dark-theme .card, so any card that sits inside an element with the dark-theme class gets the dark background. All of the card's styles, including how it looks in a dark theme, stay together in one place. Do We Always Need the &? For descendants, no. Writing .title inside the card means the same thing as writing & .title, so most people leave the ampersand off. The same goes for element names. Our card styles its image by nesting a plain img rule inside it: .card { img { width: 96px; height: 96px; } } The very first browsers to support nesting didn't allow this. A nested selector had to start with a symbol, so we had to write & img instead of img. That rule was relaxed at the end of 2023, and every current browser accepts the shorter form. If you see & in front of every nested element name in older code, that's the reason. Can We Nest Media and Container Queries? Yes, and this is one of the nicest parts of nesting. We can put @media, @container, and @supports rules directly inside a style rule. Any declarations inside them apply to the parent selector, so we don't have to repeat it. Here is the part of our recipe card that stacks the layout when the card gets narrow: .card { display: grid; grid-template-columns: 96px 1fr; @container (width < 360px) { grid-template-columns: 1fr; justify-items: center; text-align: center; img { width: 72px; height: 72px; } } } When the container holding our card gets narrower than 360 pixels, the card switches to a single column and its image shrinks. Notice that the @container block has plain declarations in it, which apply to .card, and a nested img rule, which applies to .card img. Drag the slider in the example to the left, and you'll see the layout change at that size. Without nesting, this responsive behavior would live in a separate @container block somewhere else in the file, repeating .card and .card img all over again. With nesting, the narrow layout sits right next to the regular layout it changes. How Is CSS Nesting Different From Sass? If you've written Sass, native nesting will feel very familiar. There are two places where it behaves differently, and both of them have bitten people moving their styles over. The & Isn't Text We Can Glue Onto In Sass, the & is replaced by text before anything else happens, so a lot of people use it to build class names, especially with BEM naming: /* Works in Sass, but not in native CSS */ .card { &__title { font-size: 22px; } } Sass turns this into .card__title. In native CSS, the & is a whole selector, so the browser reads &__title as "the card, which is also an element named __title." No such element exists, so nothing gets styled. In native CSS, we have to write out the full class name, like .card__title, as its own selector. Nesting Under a List Works Like :is() When the parent rule has more than one selector, the browser treats the parent like an :is() selector (https://www.kirupa.com/html5/modern_css_selectors.htm). That affects specificity, the score browsers use to decide which rule wins: [Image: A .title rule with color #b84039 nested inside a rule for #hero, .card. The browser reads it as :is(#hero, .card) .title, which scores 1 ID, 1 class, and 0 types. The ID comes from #hero, and the score is the same even when the title is inside a .card.] (https://www.kirupa.com/html5/images/nest_specificity.png) Our nested .title rule becomes :is(#hero, .card) .title, and :is() always counts as its most specific argument, which is #hero. So even when this rule styles a title inside a plain .card, it carries the weight of an ID. Sass would have produced two separate selectors, #hero .title and .card .title, each with its own score. If a nested rule mysteriously beats something it shouldn't, a selector list in the parent is a good place to look. Which Browsers Support CSS Nesting? Native nesting works in the current versions of Chrome, Edge, Firefox, and Safari, and the relaxed version that lets us nest plain element names like img has worked in all of them since the end of 2023. Nesting doesn't degrade gracefully. A browser that doesn't understand it will skip the nested rules, so the hover effects, states, and layouts inside them simply won't apply. If your site needs to support those older browsers, keep writing nested CSS but run it through a build tool, like Lightning CSS or PostCSS, that turns it back into flat rules before it ships. One last piece of advice applies no matter which browser we target. Nesting is so pleasant that it's easy to go five levels deep, and deeply nested rules produce long, very specific selectors that are hard to override later. Keeping things to two or three levels makes for CSS that's much easier to live with. Conclusion CSS nesting doesn't let us do anything new in terms of what we can style. Every nested rule we wrote in this tutorial turns into a regular selector that we could have typed out by hand. What nesting changes is where our styles live. Our recipe card's base look, its title, its hover effect, its featured state, and its narrow layout all sit inside one rule, and that rule reads like a description of the card. The parts to keep in mind are the &, which stands in for the parent selector and cares a lot about spaces, and the two Sass habits that don't carry over. Once those click, it's hard to go back to typing .card twenty times! Before you go, here are a few things you can do: 1. Test your knowledge by taking the quiz below. 2. Check out some related content: - Modern CSS Selectors: :has(), :is(), :where(), and :focus-visible (https://www.kirupa.com/html5/modern_css_selectors.htm). Style parents with :has() and group selectors with :is() and :where(). - Cascade Layers in CSS (https://www.kirupa.com/html5/css_cascade_layers.htm). Decide which group of styles wins before specificity even comes up. - Using CSS Custom Properties (Variables) with JS (https://www.kirupa.com/html5/css_variables_js_win.htm). Store values in custom properties and change them from JavaScript. 3. Stuck on something, or curious about a detail we skipped? Ask on the forums (https://forum.kirupa.com/), and we'll help you out. [Mastery Quiz] Test your knowledge! Take the Reviewing CSS Nesting Quiz: https://www.kirupa.com/quizzes/css_nesting.htm Practice with 4 multiple-choice questions and an explanation after every answer. [/Mastery Quiz]