CodeBlanks Logo Icon CodeBlanks

Nested compound

CSS course · Expert · Lesson 47/53

Learn compound selectors like &.class.

Compound selectors nested

Sometimes you need to combine the outer selector with a class: like .tab.active. Nested, &.active produces that. .tab { &.active { background: navy; } } means .tab.active { background: navy; }.

Without a space, & and .active sit side by side; both apply to the same element. Add a space and you get a descendant, which targets a different element.

Direct children with &

The direct-child combinator (>) can also be combined with &. Writing .menu { & > li { } } produces .menu > li, catching only direct li children.

Likewise & + h2 targets the next sibling and & ~ p targets all following siblings. & keeps the outer selector's name in the right spot.

Exercise Add selected and a child to the tab

Add two nested blocks inside the .tab selector: first &.selected with color: navy; second & > span direct-child selector with font-weight: 600.

Show example solution
Add two blocks inside .tab.
Example solution:
/* add selected and span inside .tab */
.tab {
  padding: 0.5rem;
  &.selected {
    color: navy;
  }
  & > span {
    font-weight: 600;
  }
}

Combining with attributes

The same idea works with attribute selectors. Writing .field { &[disabled] { opacity: 0.5; } } produces .field[disabled], catching disabled fields.

Class, attribute and pseudo-class can also combine: &.active:focus. As long as & keeps the outer selector's name in place, the combinations work as you expect.

Test yourself

  1. Write &.is-open

    .panel {
      ____ {
        display: block;
      }
    }
    Show answer
    .panel {
      &.is-open {
        display: block;
      }
    }
  2. What does &.active match?

    .tab {
      &.active { background: navy; }
    }
    • Only elements that have the .active class
    • The element that has both .tab and .active
    • An .active child inside .tab
    • The next sibling of .tab
    Show answer

    The element that has both .tab and .active — Correct. &.active becomes .tab.active; both classes apply to the same element.

All lessons in Expert