Native CSS nesting lets you write child rules inside their parent rule, just like Sass or Less, with no build step. It keeps related styles together and reduces repeated selectors.

Basic nesting

css">.lotgrafix-card {
    padding: 20px;
    border: 1px solid #ddd;

    h3 {
        margin: 0 0 10px;
    }

    p {
        color: #555;
    }
}

The & selector

Use & to refer to the parent selector. It is needed for pseudo-classes, pseudo-elements and compound selectors.

.lotgrafix-button {
    background: orangered;
    color: #fff;

    &:hover {
        background: #cc3700;
    }

    &::after {
        content: " \2192";
    }

    &.is-active {
        outline: 2px solid #000;
    }
}

Nest media queries

Place the media query inside the rule instead of repeating the selector.

.lotgrafix-grid {
    display: grid;
    grid-template-columns: 1fr;

    @media ( min-width: 768px ) {
        grid-template-columns: repeat( 2, 1fr );
    }
}

Parent context

Put & at the end to apply styles when the element is inside another one.

.lotgrafix-title {
    font-size: 1.5rem;

    .lotgrafix-dark & {
        color: #fff;
    }
}

Notes

  • Supported in all modern browsers.
  • Keep nesting to two or three levels to avoid overly specific selectors.
«
»