Topic 39 of 62
Native Nesting
Overview
For over a decade, developers refused to write raw CSS because it required constantly repeating parent class names (e.g., .card h1, .card p, .card button). We relied heavily on Sass/SCSS to 'nest' our selectors. Today, CSS Native Nesting is officially standardized in all major browsers. You can now write beautifully nested, scoped CSS exactly like you would in Sass, directly in a raw .css file.
Syntax
css
/* Standard Native Nesting */
.card {
background-color: white;
border-radius: 8px;
padding: 20px;
/* Target a child directly inside! */
h2 {
color: blue;
margin-bottom: 10px;
}
/* Target the hover state of the parent using the '&' (Ampersand) */
&:hover {
box-shadow: 0 10px 20px rgba(0,0,0,0.2);
}
/* Use '&' to append classes (equivalent to .card.active) */
&.active {
border: 2px solid green;
}
}Common Pitfalls
- Forgetting the Ampersand (
&) when dealing with state or pseudo-classes. If you writehover { color: red; }inside.card, CSS will literally look for an HTML tag called<hover>. You MUST write&:hover. - Massive over-nesting. Just because you can nest 8 levels deep doesn't mean you should. Deep nesting mathematically generates astronomically high specificity scores, making it a nightmare to override styles in mobile media queries later. Stick to a maximum of 3 levels of nesting.
Interview Questions
Q:
In native CSS nesting, what does the Ampersand (
&) character represent?A:
The Ampersand represents the exact parent selector context. It is used to explicitly chain states (&:hover), append modifiers (&.active), or change scoping order.
Real-World Example
Using nesting to scope Media Queries directly inside the component they affect, vastly improving readability.
example
css
.header-title {
font-size: 1.5rem;
color: black;
/* The Media Query is nested natively inside the component! */
@media (min-width: 768px) {
font-size: 3rem;
}
/* Dark mode scoped neatly */
.dark-theme & {
color: white;
}
}Check Your Knowledge
Test your understanding of Native Nesting with these quick questions.