Lesson 91 +10 XP

CSS Nesting

CSS Nesting

Write nested rules inside other rules, like your HTML structure. Cleaner and shorter!

Nesting is now baseline

CSS Nesting is supported in all modern browsers, so you can rely on it.

Without nesting

.card { padding: 12px; }
.card .title { font-weight: bold; }
.card .title:hover { color: hotpink; }

With nesting

.card {
  padding: 12px;
  .title {
    font-weight: bold;
    &:hover {
      color: hotpink;
    }
  }
}
  • .title is relative to .card (descendant).
  • & refers to "the parent" (the .title here).

Using &

Extra "conditions" paste to the parent:

.btn {
  background: #04aa6d;
  &:hover { background: #06945b; }
  &.is-active { outline: 2px solid; }
}

Nesting pseudo-classes

form {
  & > input:focus { border-color: blue; }
  &.loading { opacity: 0.5; }
}

Beware deep nesting

Deep nesting = higher specificity + harder reading. Keep it shallow!

TL;DR

  • Nest selectors to mirror markup.
  • & = the parent selector.
  • Baseline supported in modern browsers.
  • Keep nesting 1-2 levels deep.
  • Use it for components: less repetition, clearer code.