When your project start to grow, your stylesheet also starts to grow. At that time, keeping your stylesheet organized becomes very challenging. That’s where LESS nesting comes in picture. Nesting allows you to write CSS that mirrors your HTML structure cleaner, more readable, and far more modular than plain CSS.
In this article, we’ll break down how nesting works in LESS, when to use it, and how it helps create maintainable UI styles for modern web projects.
What Is Nesting in LESS?
Nesting in LESS lets you wrap child selectors inside parent selectors, following the same hierarchy as your HTML.
Instead of repeating selectors over and over, you group them logically in one place.
Standard CSS Example
.navbar {
background: #fff;
}
.navbar li {
display: inline-block;
}
.navbar li a {
color: #333;
}
LESS Nesting Version
.navbar {
background: #fff;
li {
display: inline-block;
a {
color: #333;
}
}
}
Same output.
Cleaner code.
Better structure.
Why Nesting Makes Your Styles Cleaner
- Mirrors Your HTML Structure: Your HTML is naturally hierarchical, so your CSS should reflect that hierarchy. Nesting helps you visualize relationships between elements.
- Reduces Repetition: LESS eliminates selector repetition, making styles shorter and easier to scan.
- Helps With Component-Based Design: Whether you’re building with React, Vue, or standard HTML, nesting fits perfectly with component-driven UI.
- Easier Maintenance: All related styles live together; you no longer have to search across files for related rules.
Using the Ampersand (&) for Contextual Nesting
The & symbol is one of the most powerful tools in LESS.
It represents the parent selector and allows for advanced nesting patterns.
Pseudo-classes
.button {
background: @primary;
&:hover {
background: darken(@primary, 10%);
}
}
Modifier Classes (BEM style)
.card {
padding: 20px;
&--highlight {
background: #fffbdd;
}
}
Chaining Selectors
.menu {
&.active {
display: block;
}
}
The ampersand makes LESS nesting powerful enough to handle modern CSS patterns like BEM, utility classes, and state-based styling.
Nesting Media Queries for Cleaner Responsive CSS
LESS allows media queries directly inside the selector where they belong.
Without LESS
@media (max-width: 768px) {
.hero-title {
font-size: 28px;
}
}
With LESS
.hero-title {
font-size: 36px;
@media (max-width: 768px) {
font-size: 28px;
}
}
This keeps responsive rules attached to the component instead of scattered across multiple files.