HTML & CSSMedium
What is nesting in CSS?
Nesting lets you write rules inside other rules so related styles live together, as in .card { & .title { } &:hover { } }. It started as a Sass feature and is now native CSS, supported in all modern browsers, where & refers to the parent selector.
Native syntax
.card {
padding: 1rem;
& h2 { margin: 0; } /* .card h2 */
.meta { color: gray; } /* .card .meta (the & is optional here) */
&:hover { outline: 2px solid; }/* .card:hover */
&.featured { border-width: 3px; } /* .card.featured */
.dark & { background: #111; } /* .dark .card */
@media (width >= 40em) { padding: 2rem; }
}
Differences from Sass
- Native nesting behaves like
:is(): the parent selector is wrapped in:is(...), so specificity follows:is()rules (it takes the most specific selector in a list). - No string concatenation: Sass's
&__title(BEM-style) does not work natively. - Nested at-rules (
@media,@container,@supports,@layer) are supported.
Best practices
- Keep it shallow (two or three levels). Deep nesting creates long, highly specific selectors that are hard to override, the main problem with Sass nesting too.
- Nest states, pseudo-elements and media queries for a component; avoid mirroring the whole DOM tree.
- Older browsers need a build step (PostCSS or Lightning CSS can flatten nesting).
Interview tip
Mention that it is now native and point out the BEM &__ difference; it shows up-to-date knowledge.
Code example
html
1<style>2 body { font-family: system-ui; }3 .card {4 max-width: 300px;5 padding: 12px;6 border: 2px solid #0b1020;7 border-radius: 10px;8 margin-bottom: 12px;910 & h3 { margin: 0 0 6px; color: #2b4bff; }11 .meta { color: #64748b; font-size: .875rem; }12 &:hover { box-shadow: 4px 4px 0 #0b1020; }13 &.featured { background: #fef9c3; }14 &:has(img) { padding: 0; overflow: hidden; }15 & img { width: 100%; display: block; }1617 @media (width >= 600px) { max-width: 420px; }18 }19</style>20<article class="card"><h3>Nested styles</h3><p class="meta">All rules live inside .card</p></article>21<article class="card featured"><h3>Featured</h3><p class="meta">&.featured</p></article>22<article class="card"><img src="https://picsum.photos/id/1047/600/200" alt="City street" width="600" height="200"></article>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.