Sass Nesting

Sass Tutorial

Sass Nesting

Sass Nesting allows you to write CSS selectors inside other selectors, following the same hierarchy as your HTML structure.
This makes your code cleaner, more readable, and better organized compared to plain CSS.


Basic Nesting Example

Sass (.scss)


 

Compiled CSS


 Nesting Reflects HTML Structure

HTML

<nav>
<ul>
<li><a href="#">Home</a></li>
</ul>
</nav>

✔ Sass nesting matches the DOM hierarchy naturally.


Nesting with Classes

.card {
padding: 20px;
.title {
font-size: 18px;
}.content {
color: #555;
}
}

Parent Selector (&)

The & symbol refers to the parent selector.

Hover Example

button {
background: blue;
&:hover {
background: darkblue;
}
}

Modifier Example (BEM style)

.alert {
padding: 10px;
&-success {
background: green;
}&-danger {
background: red;
}
}

Output:

.alert-success { background: green; }
.alert-danger { background: red; }

Nesting Pseudo-Classes

input {
border: 1px solid #ccc;
&:focus {
border-color: blue;
}
}

Nesting Media Queries

.container {
width: 100%;
@media (max-width: 768px) {
width: 90%;
}
}

✔ Keeps responsive styles near the main styles.


Nesting Properties (Optional Syntax)

font: {
size: 16px;
weight: bold;
}

Compiles to:

font-size: 16px;
font-weight: bold;

❌ Over-Nesting (Bad Practice)

nav {
ul {
li {
a {
span {
color: red;
}
}
}
}
}

⚠️ Avoid nesting more than 3 levels.


✅ Best Practices

✔ Nest only when logical
✔ Use & wisely
✔ Avoid deep nesting
✔ Keep code readable


📌 Summary

  • Sass nesting mirrors HTML structure

  • Reduces repetition

  • Improves readability

  • Over-nesting should be avoided

You may also like...