Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 11.1 — CSS Nesting
CSS · Example 1 of 3 Baseline 2023+

A component written with nesting

The nested p rule only reaches paragraphs inside the card, so .outside keeps the default black. Adding the class featured turns on &.featured, which means .card.featured.

Native CSS nesting lets you write a rule inside another rule, so styles for a component and its parts live together; & stands for the parent selector, and every nested selector behaves as if the parent were wrapped in :is(), which decides its specificity.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Rewrite this with nesting: .nav { display: flex; } .nav a { color: white; } .nav a:hover { color: gold; } .nav a.active { font-weight: bold; }

02

Inside a .btn rule, write nested CSS that gives the button a red background when it is inside an element with the class danger-zone, and a 20px top margin when it directly follows another .btn.

03

A stylesheet has .list { li { color: navy; } } and later ul li { color: teal; }. What colour is an li inside <ul class="list">, and why?

Explain it without notes

01

What does & mean in native CSS nesting, and when must you write it?

02

How is the specificity of a nested selector calculated? Give an example where it surprises people.

03

What are the differences between native CSS nesting and Sass nesting?

04

Why do style guides limit nesting depth?

A component written with nesting Baseline 2023+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

.card .title: rgb(67, 56, 202)
.card p: rgb(55, 65, 81)
.outside: rgb(0, 0, 0)
featured background: rgb(238, 242, 255)