nesting
CSS syntax for writing selectors nested inside other selectors. Nesting you used to write in Sass and compile now works directly in the browser.
Modern approach
Write descendant, state, and media query rules together inside the parent rule. It works directly in the browser without a build step.
.card {
padding: 16px;
.title {
font-size: 1.25rem;
}
&:hover {
background-color: #f5f5f5;
}
@media (min-width: 768px) {
padding: 24px;
}
}Legacy approach
Plain CSS required repeating the parent selector for every rule. To write nested rules, you wrote them in Sass or a similar tool and compiled them into CSS like this.
.card {
padding: 16px;
}
.card .title {
font-size: 1.25rem;
}
.card:hover {
background-color: #f5f5f5;
}
@media (min-width: 768px) {
.card {
padding: 24px;
}
}Things to watch when replacing
- You can’t join selectors like Sass’s
&__title. Such rules are ignored, so write BEM elements as full selectors such as.card__title. - The specificity of a nested rule is the highest one in the parent selector list, just like
:is(). In the example below,.linkinside.sidebaralso gets the specificity of#main, so it beats.nav .linkwritten later. In Sass, it expanded to.sidebar .link, so.nav .linkwon. - Declarations written after nested rules apply in written order from Chrome 130, Firefox 132, and Safari 18.2. Earlier versions move them before the nested rules, so put declarations before any nested rules.
- Nested rules starting with a type selector without
&(such asli { }) work from Chrome 120 and Safari 17.2. Earlier versions needed& li. - If a nested rule is invalid, only that rule is ignored. The parent’s declarations still apply.
#main,
.sidebar {
& .link {
color: blue;
}
}
.nav .link {
color: red;
}
Fallback
All five target browsers support it, so you normally don’t need to compile it. Browsers without support ignore nested rules entirely. If you also have to support older browsers, use a build tool such as PostCSS to convert it into the flat CSS shown in the legacy approach.
Browser Support
Chrome
v120+2023-12-05Edge
v120+2023-12-07Safari
v17.2+2023-12-11Safari (iOS)
v17.2+2023-12-11Firefox
v117+2023-08-29