Nesting Styles
Nest CSS selectors inside each other — write cleaner, more readable stylesheets that mirror HTML structure.
Nesting Styles
SASS lets you nest selectors inside each other, mirroring the HTML structure. This makes your stylesheets more organised and readable.
Basic Nesting
// SCSS
.navbar {
background: #2c3e50;
padding: 15px;
ul {
list-style: none;
display: flex;
margin: 0;
padding: 0;
}
li {
margin-right: 20px;
}
a {
color: white;
text-decoration: none;
font-size: 14px;
}
}
/* Compiled CSS */
.navbar { background: #2c3e50; padding: 15px; }
.navbar ul { list-style: none; display: flex; margin: 0; padding: 0; }
.navbar li { margin-right: 20px; }
.navbar a { color: white; text-decoration: none; font-size: 14px; }
The & (Parent Selector)
The & character references the parent selector. Essential for pseudo-classes, modifiers, and BEM naming:
.button {
background: #3498db;
color: white;
padding: 10px 20px;
border: none;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s;
// &:hover → .button:hover
&:hover {
background: #2980b9;
transform: translateY(-1px);
}
// &:active → .button:active
&:active {
transform: translateY(0);
}
// &:focus → .button:focus
&:focus {
outline: 3px solid rgba(52, 152, 219, 0.4);
}
// &.primary → .button.primary
&.primary {
background: #3498db;
}
// &.danger → .button.danger
&.danger {
background: #e74c3c;
}
// &--large → .button--large (BEM modifier)
&--large {
padding: 14px 28px;
font-size: 18px;
}
}
& for BEM Naming
// BEM: Block__Element--Modifier
.card {
background: white;
border-radius: 12px;
// .card__header
&__header {
padding: 20px;
border-bottom: 1px solid #eee;
}
// .card__body
&__body {
padding: 20px;
}
// .card__footer
&__footer {
padding: 15px 20px;
background: #f8f9fa;
}
// .card--featured
&--featured {
border: 2px solid #3498db;
}
}
Nesting Properties
// Nest properties that share a prefix:
.banner {
font: {
family: 'Inter', sans-serif;
size: 24px;
weight: 700;
}
border: {
radius: 12px;
color: #ddd;
style: solid;
width: 2px;
}
}
⚠️ Don't Over-Nest!
// ❌ BAD — too deeply nested (creates overly specific selectors)
.page {
.container {
.sidebar {
.nav {
.nav-item {
a {
color: blue;
}
}
}
}
}
}
// Compiles to: .page .container .sidebar .nav .nav-item a { }
// That's 6 levels deep and very hard to override!
// ✅ GOOD — keep nesting to 3 levels max
.nav {
list-style: none;
&-item {
margin-bottom: 5px;
}
a {
color: blue;
&:hover { color: darkblue; }
}
}
The Rule of Three
Never nest more than 3 levels deep. If you need deeper nesting, restructure your selectors.
Key Takeaways
- Nesting places child selectors inside parent blocks
&references the parent selector — essential for:hover,:focus, and BEM&.class= same element with extra class&__elementand&--modifier= BEM naming pattern- Limit nesting to 3 levels — deeper creates over-specific selectors
- Nesting mirrors HTML structure but don't replicate all of it