Sass Nesting
Nesting lets you write CSS rules inside other rules, in the same shape as your HTML.
Basic Nesting
In plain CSS you must repeat the parent selector again and again: nav ul, nav li, nav a. In Sass, you write the child rules inside the parent:
Example
nav {
background-color: #222;
ul {
margin: 0;
padding: 0;
list-style: none;
}
li {
display: inline-block;
}
a {
color: white;
padding: 10px 15px;
text-decoration: none;
}
}nav {
background-color: #222;
}
nav ul {
margin: 0;
padding: 0;
list-style: none;
}
nav li {
display: inline-block;
}
nav a {
color: white;
padding: 10px 15px;
text-decoration: none;
}Each nested selector becomes a descendant selector in the CSS, with a space between the parent and the child.
The Parent Selector &
The & symbol means "the parent selector itself". Use it when you do not want a space, for example for pseudo-classes like :hover, extra classes and name endings.
Example
.btn {
background-color: #cc6699;
color: white;
&:hover {
background-color: #b34d80;
}
&.disabled {
opacity: 0.5;
}
&-large {
font-size: 20px;
}
}.btn {
background-color: #cc6699;
color: white;
}
.btn:hover {
background-color: #b34d80;
}
.btn.disabled {
opacity: 0.5;
}
.btn-large {
font-size: 20px;
}| You write | You get | Meaning |
|---|---|---|
&:hover | .btn:hover | The button when hovered |
&.disabled | .btn.disabled | A button that also has class disabled |
&-large | .btn-large | A new class name that starts with btn |
:hover (without &) | .btn :hover | Any hovered element inside the button (usually a bug) |
Child, Sibling and Media Queries
You can nest selectors that start with > or +, and you can even nest a media query. Sass moves the media query out and puts the right selector inside it.
Example
.card {
padding: 20px;
> h2 {
margin-top: 0;
}
+ .card {
margin-top: 16px;
}
@media (max-width: 600px) {
padding: 10px;
}
}.card {
padding: 20px;
}
.card > h2 {
margin-top: 0;
}
.card + .card {
margin-top: 16px;
}
@media (max-width: 600px) {
.card {
padding: 10px;
}
}Keeping the phone style right next to the normal style makes the code easier to follow.
Property Nesting
Properties that share a first word, such as font-family, font-size and font-weight, can be nested too. This is used less often, but you may see it:
Example
.title {
font: {
family: Georgia, serif;
size: 24px;
weight: bold;
}
}.title {
font-family: Georgia, serif;
font-size: 24px;
font-weight: bold;
}Do Not Nest Too Deep
Every level of nesting makes the CSS selector longer and stronger. Deep nesting like .page .content .sidebar .menu ul li a is hard to override later and ties your CSS tightly to the HTML.
A good rule: do not nest more than three levels deep. If you need more, give the element its own class.
Exercise
Exercise
Inside .link { ... }, what CSS selector does &:hover produce?
