Sub topic 1
Writing a rule inside a rule
Prerequisites
This chapter assumes you already know:
- CSS selectors: class, type, attribute, and pseudo-class selectors.
- The three combinators: descendant (a space), child (
>), and sibling (+and~). - The basics of the cascade and specificity, meaning how the browser picks a winner when two rules set the same property.
- How a media query is written.
You don't need Sass or any other preprocessor. If you have used one, the last section lists the habits that don't carry over. The chapters that follow cover the differences in detail.
What nesting solves
Without nesting, every rule repeats the full selector of the element it styles:
.card {
padding: 1rem;
border: 1px solid #ccc;
}
.card .title {
font-weight: 600;
}
.card:hover {
border-color: #666;
}The string .card appears three times. If you rename the class, you must change every copy. The three rules also sit apart from each other in the file, so a reader has to infer that they belong together.
Native CSS nesting lets you write the child rules inside the parent rule. The browser reads the nested selectors in relation to the parent selector. No build step is involved. The browser itself does the work.
The basic form
Here is the same stylesheet with nesting:
.card {
padding: 1rem;
border: 1px solid #ccc;
& .title {
font-weight: 600;
}
&:hover {
border-color: #666;
}
}This is the same as the flat version above. The nested rules are scoped to .card:
& .titleis equivalent to.card .title.&:hoveris equivalent to.card:hover.
The & is the nesting selector. It stands for "the selector of the parent rule." When the browser matches a nested rule, it substitutes the parent's selector for each &. The next chapter covers & in depth. For now, treat it as a placeholder for the parent.
A rule block can hold two kinds of content:
- Declarations, such as
padding: 1rem;, which apply to the elements the parent selector matches. - Nested rules, such as
& .title { ... }, which each have their own selector and their own declarations.
A complete example you can run
Save this as card.html and open it in a current browser:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Nesting demo</title>
<style>
.card {
padding: 1rem;
border: 1px solid #ccc;
max-width: 20rem;
& .title {
font-weight: 600;
margin: 0 0 0.5rem;
}
& .body {
color: #444;
}
&:hover {
border-color: #666;
}
}
</style>
</head>
<body>
<div class="card">
<h2 class="title">Nested rules</h2>
<p class="body">Hover over this card to darken its border.</p>
</div>
</body>
</html>The title is bold and the body text is grey. The border darkens when you hover over the card. The .title and .body rules apply only inside .card. A .title element elsewhere on the page would be unaffected.
How the browser reads a nested rule
Nesting is not a text substitution done before parsing. The browser parses the nested rule as a real rule that belongs to its parent. Each nested selector is combined with the parent selector when the browser matches it against elements. The diagram shows that resolution for one nested rule.
The resolved selector behaves as if you had written it out in full. The "as if" is not exact. When the parent is a selector list or uses an ID, the specificity differs from what text substitution would give. The specificity chapter explains this.
Nested rules can nest further
A nested rule can contain its own nested rules. Each level resolves against the level above it:
.card {
& .footer {
border-top: 1px solid #ddd;
& a {
color: #06c;
&:hover {
text-decoration: underline;
}
}
}
}This resolves to three rules:
.card .footer.card .footer a.card .footer a:hover
The & in &:hover stands for the whole resolved parent, .card .footer a. It does not stand for just a.
Nested rules and the cascade
A nested rule is an ordinary rule once resolved, so the normal cascade applies:
- Source order still breaks ties between rules of equal specificity.
- Specificity is computed from the resolved selector.
- Inheritance,
!important, and layers behave as usual.
Nesting does not create a new scope for styles. .card .title matches any .title element inside any .card, wherever it appears. Nesting is a way of writing selectors, not an isolation mechanism.
Nested rules inside nested rules do not leak outward
A nested rule applies only where its resolved selector matches. Suppose you write this:
.sidebar {
& .title {
font-size: 0.9rem;
}
}
.card {
& .title {
font-size: 1.2rem;
}
}The two .title rules don't conflict. One applies inside .sidebar and the other inside .card. An element that is inside both would match both, and then source order decides.
Nesting other kinds of rules
Style rules are not the only thing you can nest. You can also put conditional at-rules, such as @media and @supports, inside a style rule. Declarations inside them apply to the parent selector when the condition matches:
.panel {
display: block;
@media (min-width: 40rem) {
display: grid;
grid-template-columns: 1fr 2fr;
}
@supports (container-type: inline-size) {
container-type: inline-size;
}
}Here the @media block does not need a repeated .panel selector. Its declarations apply to .panel when the viewport is at least 40rem wide. A later chapter covers conditional at-rules, including @container and @layer.
Declarations and nested rules together
You can put declarations before, between, or after nested rules. The usual style is to write the parent's own declarations first and the nested rules after them. That keeps a rule easy to scan.
.button {
background: #06c;
color: white;
&:hover {
background: #049;
}
&:disabled {
opacity: 0.5;
}
}Browsers have changed how they handle declarations written after a nested rule. Older implementations moved those declarations up, as if they were written before the nested rules. Current implementations keep them in the order you wrote them. If you need to support a range of browsers, put all of the parent's declarations first. The chapter on declaration order covers the exact behavior.
Common mistakes
Forgetting that nested rules are relative
A nested selector is always relative to the parent. This rule styles only .title elements inside .card:
.card {
& .title {
font-weight: 600;
}
}If you wanted every .title on the page, don't nest it. Put the rule at the top level.
Writing a space where none is wanted
& .title (with a space) means "a .title descendant of the parent." &.title (no space) means "the parent itself, when it also has the class title." One missing space changes which elements match. The chapter on compound selectors covers this.
Closing braces in the wrong place
A missing } is the most common nesting error, because the nested block is easy to leave open. A stray brace can cause the browser to drop later rules. Format your code consistently and let your editor match braces.
An invalid nested selector
If a nested rule has an invalid selector, the browser ignores that nested rule. The parent rule and its other nested rules still apply. Check the browser's developer tools if a nested rule seems to have no effect. The Styles panel shows which rules matched and which were dropped.
Browser support in brief
Native nesting is supported in current versions of Chrome, Edge, Firefox, and Safari. The earliest versions of the feature had a stricter syntax. In those versions a nested selector could not begin with a bare type selector such as a without an & in front of it. Writing & a works in all of them. The relaxed syntax chapter explains when you can omit the &. The browser support chapter covers fallbacks.
A browser that doesn't understand nesting ignores the nested rules. It still applies the parent's own declarations, so a page degrades but doesn't break.
Differences from Sass you will notice immediately
If you have used a preprocessor, three differences matter from the start:
- Native nesting runs in the browser. The nested rules are present in the stylesheet that ships to users, not flattened at build time.
- You can't build selectors by gluing strings together. In Sass,
&-titleproduces.card-title. In native CSS,&-titleis invalid. - Nested rules are parsed as rules, so specificity follows CSS selector semantics, not text substitution.
Later chapters cover these differences in detail.
Summary
- A nested rule is written inside a parent rule's braces and styled relative to the parent's selector.
- The
&nesting selector stands for the parent's selector. - The result is equivalent to the flat rule you would otherwise write, with some exceptions around specificity.
- Nested rules can themselves nest, and
&always refers to the full resolved parent. - Conditional at-rules such as
@mediacan nest inside a style rule. - Nesting is a syntax convenience. It doesn't isolate styles.
Exercise
Write the flat (non-nested) equivalent of this rule. .menu { margin: 0; & .item { padding: 0.5rem; } &:focus-within { outline: 2px solid #06c; } }
Show answer
.menu { margin: 0; } .menu .item { padding: 0.5rem; } .menu:focus-within { outline: 2px solid #06c; }
Exercise
A page has <div class="card"><h2 class="title">A</h2></div> and <aside class="sidebar"><h2 class="title">B</h2></aside>. You write .card { & .title { color: red; } }. Which heading turns red, and why?
Show answer
Only heading A. The nested selector resolves to .card .title, which matches .title elements that are descendants of .card. Heading B is inside .sidebar, so it doesn't match.
Exercise
What is the difference in meaning between & .title and &.title when nested inside .card?
Show answer
& .title resolves to .card .title, which matches a .title element inside a .card. &.title resolves to .card.title, which matches a single element that has both the card and title classes.