Deel 6: The power of design
Nested CSS

CSS nesting
CSS Nesting
/* No nesting */
article.card {
border: 1px solid lightgrey;
border-radius: 6px;
overflow: hidden;
}
article.card header {
border-bottom: 1px solid lightgrey;
background: #f1f3f4;
padding: 16px;
}
/* With nesting */
article.card {
border: 1px solid lightgrey;
border-radius: 6px;
overflow: hidden;
header {
border-bottom: 1px solid lightgrey;
background: #f1f3f4;
padding: 16px;
}
}
Multi-level nesting
article.card {
border: 1px solid lightgrey;
border-radius: 6px;
overflow: hidden;
header {
border-bottom: 1px solid lightgrey;
background: #f1f3f4;
padding: 16px;
h2 {
margin: 0;
}
}
}
& Nesting
a {
&:hover {
/* a:hover */
}
:hover {
/* a :hover */
}
}
Compound selectors
.a {
/* styles for element with class="a" */
.b {
/* styles for element with class="b" which is a descendant of class="a" */
}
&.b {
/* styles for element with class="a b" */
}
}
/* the browser parses this as */
.a {
/* styles for element with class="a" */
}
.a .b {
/* styles for element with class="b" which is a descendant of class="a" */
}
.a.b {
/* styles for element with class="a b" */
}
& after
<div class="wrapper">
<article class="card">
<h2>Card 1</h2>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit.</p>
</article>
<article class="card featured">
<h2>Card 2</h2>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit.</p>
</article>
</div>
.card {
padding: 0.5rem;
border: 1px solid black;
border-radius: 0.5rem;
h2 {
/* equivalent to `.card h2` */
color: slateblue;
.featured & {
/* equivalent to `:is(.card h2):is(.featured h2)` */
color: tomato;
}
}
}
& after - result

Nesting media queries
.header {
font-size: 2rem
@media (max-width: 47.5rem ) {
{
font-size: 1.5rem;
}
}
}
Nested CSS
By Lecturer GDM
Nested CSS
CSS Nested
- 210