Sass — Nesting
Basic nesting
nav {
background: #333;
ul {
margin: 0;
list-style: none;
}
li {
display: inline-block;
}
a {
color: white;
text-decoration: none;
&:hover {
color: #3498db;
}
}
}
Parent selector &
.card {
&-title { font-size: 24px; }
&-body { padding: 20px; }
&-footer { border-top: 1px solid #ccc; }
&:hover { box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
&.active { border-color: #3498db; }
}
Pseudo-classes
.button {
background: #3498db;
color: white;
&:hover { background: #2980b9; }
&:active { background: #1f6dad; }
&:focus { outline: 2px solid #3498db; }
&:disabled { opacity: 0.5; }
}
Pseudo-elements
.link {
color: #3498db;
&::after {
content: ' →';
margin-left: 4px;
}
&::before {
content: '';
display: inline-block;
width: 8px;
height: 8px;
margin-right: 8px;
}
}
Descendant selectors
.form {
input {
padding: 10px;
border: 1px solid #ccc;
&:focus {
border-color: #3498db;
}
}
label {
display: block;
margin-bottom: 4px;
}
}
Nested properties
.font {
family: 'Helvetica', sans-serif;
size: 16px;
weight: bold;
&-large { size: 24px; }
&-small { size: 12px; }
}
// Compiles to:
// .font { font-family: ...; font-size: 16px; font-weight: bold; }
Group selectors
.header, .footer {
padding: 20px;
h1, h2, h3 {
margin: 0;
}
}
Deep nesting warning
// Avoid this - output gets large
.page {
.header {
.nav {
.link {
color: red; // .page .header .nav .link
}
}
}
}
// Better - keep nesting shallow
.nav-link {
color: red;
}
Mini Practice
- Nest a card component with title, body, footer
- Add hover states with &
- Create pseudo-element styles
- Use nested properties for font shorthand
Up Next
Continue with Mixins — reusable style blocks with parameters.
Related Topics
Frequently Asked Questions about Nesting
What is Nesting in Sass?
Nesting is a fundamental concept in Sass. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Nesting?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Nesting.
Why is Nesting important in Sass?
Nesting is essential for Sass development. Understanding this concept will help you write better code and solve real-world problems more effectively.