Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Nesting and &

Nesting lets you write a rule inside another rule, following the structure of the HTML. Less joins the selectors during compilation. The styles of one component stay in one block, and you do not have to type .card again and again.

Nested rules

Write the card styles in styles/components/cards.less:

// styles/components/cards.less
.card {
  padding: 16px;
 
  .title {
    margin: 0;
  }
 
  p {
    color: #4b5563;
  }
}
.card {
  padding: 16px;
}
.card .title {
  margin: 0;
}
.card p {
  color: #4b5563;
}

The inner rule became a descendant selector: .card .title means .title anywhere inside .card.

The parent reference &

The & symbol means "the parent selector". You need it when there must be no space between the selectors — for pseudo-classes and compound classes:

// styles/components/buttons.less
.btn {
  background: #2563eb;
 
  &:hover {
    background: #1d4ed8;
  }
 
  &.active {
    outline: 2px solid black;
  }
}
.btn {
  background: #2563eb;
}
.btn:hover {
  background: #1d4ed8;
}
.btn.active {
  outline: 2px solid black;
}

Without & the result would be .btn :hover with a space — hovering over any descendant of the button.

Modifiers and the parent at the end

& can be joined with text, as in BEM names, and placed at the end of a selector:

// styles/components/buttons.less
.btn {
  color: white;
 
  &-large {
    padding: 12px 24px;
  }
 
  .dark & {
    color: black;
  }
}
.btn {
  color: white;
}
.btn-large {
  padding: 12px 24px;
}
.dark .btn {
  color: black;
}
<style>
  .btn {
    color: white;
  }
  .btn-large {
    padding: 12px 24px;
  }
  .dark .btn {
    color: black;
  }
</style>
 
<button class="btn btn-large" style="background: #2563eb">Normal theme</button>
<div class="dark" style="padding: 8px">
  <button class="btn btn-large" style="background: #facc15">Dark theme</button>
</div>

&-large produced the class .btn-large, and .dark & a rule for a button inside an element with the class dark.

Media queries inside a rule

@media can be nested right inside a rule. Less moves it out and repeats the selector:

// styles/components/cards.less
.card {
  padding: 16px;
 
  @media (min-width: 768px) {
    padding: 32px;
  }
}
.card {
  padding: 16px;
}
@media (min-width: 768px) {
  .card {
    padding: 32px;
  }
}

This keeps everything about the card, including responsiveness, in one place.

Common mistake

Deep nesting "like the HTML" produces long selectors with high specificity:

// styles/components/cards.less
.page {
  .content {
    .card {
      .title {
        color: #111827;
      }
    }
  }
}
.page .content .card .title {
  color: #111827;
}

Such a selector is hard to override and breaks with any change to the markup. Keep nesting to two or three levels and nest only what really depends on the parent.

Thanks for reading!

Donate to the site — we work hard for you.