SyntaxStudy
Sign Up
SASS / SCSS Basic Nesting and the Parent Selector
SASS / SCSS Beginner 1 min read

Basic Nesting and the Parent Selector

SASS nesting lets you write CSS rules inside other rules, mirroring the hierarchy of your HTML. This eliminates the repetition of selector prefixes and makes the relationship between styles visually clear. For example, instead of writing `nav ul`, `nav li`, and `nav a` as three separate rules, you nest `ul`, `li`, and `a` inside `nav`. The `&` symbol is the parent selector. When used inside a nested rule, `&` is replaced with the full parent selector during compilation. This makes it easy to write pseudo-classes like `&:hover`, pseudo-elements like `&::before`, and modifier classes like `&.is-active` without duplicating the full selector. The parent selector also enables BEM (Block Element Modifier) notation cleanly. `&__element` produces a selector like `.card__element` and `&--modifier` produces `.card--modifier`. This pattern keeps all related styles together in one nested block, making components very easy to find and maintain.
Example
// ── Basic nesting ─────────────────────────────────────────────────────────────

nav {
    background: #2c3e50;
    padding   : 0 1rem;

    ul {
        display  : flex;
        list-style: none;
        margin   : 0;
        padding  : 0;
    }

    li { margin-right: 0.5rem; }

    a {
        color          : #ecf0f1;
        text-decoration: none;
        padding        : 0.75rem 1rem;
        display        : block;

        // & is replaced by "nav a" during compilation
        &:hover  { color: #3498db; }
        &:focus  { outline: 2px solid #3498db; }
        &.active { font-weight: 700; border-bottom: 2px solid #3498db; }
    }
}

// ── BEM with the parent selector ─────────────────────────────────────────────
.card {
    border-radius: 8px;
    padding      : 1.5rem;
    background   : #fff;
    box-shadow   : 0 2px 8px rgba(0,0,0,.1);

    // &__element → .card__element
    &__header { font-size: 1.25rem; font-weight: 700; margin-bottom: 1rem; }
    &__body   { font-size: 1rem; line-height: 1.6; }
    &__footer { margin-top: 1.5rem; border-top: 1px solid #eee; padding-top: 1rem; }

    // &--modifier → .card--modifier
    &--featured { border: 2px solid #3498db; }
    &--dark     { background: #2c3e50; color: #ecf0f1; }
}