Introduction
Nesting selectors helps keep related styles together. It makes your code cleaner and easier to read.
Nesting selectors helps keep related styles together. It makes your code cleaner and easier to read.
$selector {
property: value;
nested-selector {
property: value;
}
}.button { color: blue; &:hover { color: red; } }
.menu { background: white; .item { padding: 1rem; } }
.card { border: 1px solid #ccc; .title { font-weight: bold; } .content { margin-top: 0.5rem; } }
This example shows a card with nested styles for its title, content, and hover background color. Nesting keeps related styles inside the .card block.
@use 'sass:color'; .card { border: 2px solid #333; padding: 1rem; background: color.scale(#eee, $lightness: -10%); .title { font-size: 1.5rem; font-weight: bold; color: #222; } .content { margin-top: 0.5rem; color: #555; } &:hover { background: color.scale(#eee, $lightness: 10%); } }
Always indent nested styles properly to avoid confusion.
Use & to refer to the parent selector inside nested blocks.
Nesting helps reduce repeated selectors and keeps styles organized.
Nesting groups related styles inside one block.
Use & to refer to the parent selector for states like :hover.
It makes your styles easier to read and maintain.
:hover style inside a button class?& refers to the parent selector. To nest :hover, write .button { &:hover { ... } }.& or place pseudo-class incorrectly..card {
background: white;
&:hover {
background: gray;
}
.title {
font-weight: bold;
}
}&:hover becomes .card:hover. The nested .title becomes .card .title..nav {
color: black;
&:hover {
color: blue;
}
&.active {
color: red;
}
.item {
font-size: 1rem;
}
&:item {
font-weight: bold;
}
}&:hover and &.active are valid. .item nested inside .nav is correct.&:item is invalid because :item is not a valid pseudo-class. It should be .item without &:.&:hover .title to style the title when the card is hovered, which is correct. .card {
background: white;
&:hover {
.title {
background: lightgray;
color: blue;
}
}
.title {
color: black;
}
} nests .title inside &:hover but incorrectly applies background: lightgray to .title instead of the card. .card {
background: white;
.title {
color: black;
&:hover {
color: blue;
}
}
&:hover {
background: lightgray;
}
} incorrectly applies hover on .title itself. .card {
background: white;
&:hover {
background: lightgray;
}
.title:hover {
color: blue;
}
.title {
color: black;
}
} styles .title:hover, which triggers only when hovering the title, not the card.Pass the test and this pattern moves unknown