skip to content

In Sass, what CSS do a %placeholder with @extend and a mixin each emit for shared styles, and why can't @extend reach across @media?

level: seniorimportance: should knowfreq 10%

answer

  1. copying versus selector grouping
  2. placeholders never print alone
  3. position of the extended rule
  4. media context must match
  5. mixins take arguments

basics

~20 s

A mixin copies its declarations into every rule that includes it. @extend adds the extending selector to the existing rules, so a %placeholder yields one grouped rule. Inside @media, @extend can only reach selectors in that same media context.

solid answer

~50 s

`@include` pastes a mixin's declarations into each including rule, so ten includes emit ten copies, but each can take arguments. `@extend %card-base` works the other way: it rewrites the rules that contain `%card-base` so they also carry the extending selector, producing one rule such as `.event-card, .news-card { … }`, and a selector containing a placeholder is never printed on its own. Because the shared declarations stay where the extended rule is, their cascade position is that rule's, not the `@extend`'s. Inside `@media`, `@extend` may only extend selectors in the same at-rule: extending a top-level selector from a media query is an error, since Sass cannot keep the condition without duplicating the whole rule. Use `@extend` for semantic is-a relationships (`.error--serious` is an `.error`) and mixins for configurable or non-semantic bundles; compression makes the extra mixin output cheap.

code

scss · 18 lines
scss
%card-base {
  padding: 1rem;
  border: 1px solid #d0d7de;
}

@mixin card-shadow($depth: 1) {
  box-shadow: 0 ($depth * 2px) ($depth * 4px) rgba(0, 0, 0, 0.15);
}

.event-card {
  @extend %card-base;
  @include card-shadow;
}

.news-card {
  @extend %card-base;
  @include card-shadow(2);
}

go deeper

for a junior

Recall that a mixin copies declarations, that @extend groups selectors, and that a %placeholder appears in the output only through the selectors that extend it.

for a middle

Explain the emitted CSS for both, where extended declarations sit in the cascade, and why @extend inside @media cannot target a top-level selector.

for a senior

Spot the production surprises of @extend: cascade order taken from the extended rule, selector lists growing across a codebase, missing-target errors and media-context errors.

for a principal

Set the library convention: extends only for semantic is-a relationships close to their target, mixins elsewhere, accepting extra bytes that compression largely absorbs.

## Two ways to share styles Sass gives two tools for "these rules should look alike": a **mixin**, which copies declarations, and **`@extend`**, which shares a rule by grouping selectors. They produce visibly different CSS, sit differently in the cascade, and have different limits. ## What a mixin emits ```scss @mixin card-shadow($depth: 1) { box-shadow: 0 ($depth * 2px) ($depth * 4px) rgba(0, 0, 0, 0.15); } .event-card { @include card-shadow; } .news-card { @include card-shadow(2); } ``` Each `@include` pastes the declarations into the including rule, so the output has one `box-shadow` inside `.event-card` and another inside `.news-card`. Duplication grows with every include, but the Sass docs point out that servers compress CSS with an algorithm that is very good at repeated text, so mixins rarely change download size much. In exchange, mixins take arguments and work in any context, including inside a media query. ## What @extend emits `@extend <selector>` tells Sass that one selector should be styled as if it also matched another. Sass does not copy anything: it **edits the rules that contain the extended selector** so that they also carry the extending selector, unifying selectors intelligently so it never generates combinations that cannot match. - **Placeholder selectors** (`%card-base`) look like classes but start with `%`. A selector containing a placeholder is never printed; only the selectors that extend it are. So `%card-base { padding: 1rem; }` extended by `.event-card` and `.news-card` becomes one rule with the selector list `.event-card, .news-card`. - **Cascade position.** The shared declarations sit where the extended rule is written, *not* where the `@extend` appears: the same precedence they would have if you had added the extended class to the element's HTML. - **Mandatory by default.** If no rule contains the extended selector, Sass reports an error, which catches typos and renames; `!optional` makes the extend do nothing instead. - **Scope.** Under `@use`, an extension affects only rules in upstream modules: those the stylesheet loads with `@use` or `@forward`, and what they load in turn. Under the deprecated `@import`, extensions were global. - **Private placeholders** (`%-base`, `%_base`) can be extended only inside the stylesheet that defines them. ## Why @extend stops at @media `@extend` is allowed inside `@media`, but only for selectors that appear inside the same media context: ```scss %card-base { padding: 1rem; } @media (min-width: 48rem) { .wide { @extend %card-base; } // error: %card-base is outside this @media } ``` The reason is mechanical. Extending works by adding `.wide` to the selector list of the `%card-base` rule. That rule lives at the top level, so adding `.wide` there would apply the styles at every width and lose the media condition. The only correct output would be a duplicate of the whole rule inside the media query, which is what a mixin does and what `@extend` deliberately never does. So Sass refuses. The fixes are to use a mixin for styles needed inside a media query, or to define the placeholder inside the same media block. ## Other limits worth knowing 1. Only **simple selectors** (`.info`, `a`, `%base`) can be extended; Dart Sass rejects `@extend .message.info` and `@extend .main .info`. 2. Extends are resolved **after parent selectors**, so `@extend .card` does not affect `.card { &__title { … } }`: the nested rule compiles to `.card__title`, a different selector. 3. When interleaving complex selectors, Sass uses a heuristic and does not generate every possible combination of ancestors. ## Choosing | Question | Mixin | `@extend` with a `%placeholder` | |---|---|---| | Output | Declarations copied into each rule | One rule with a grouped selector list | | Arguments | Yes | No | | Cascade position | Where the `@include` is written | Where the extended rule is written | | Inside `@media` | Works anywhere | Only for selectors in the same media context | | Missing target | Not applicable | Error unless `!optional` | | Best for | Configurable or non-semantic bundles | Semantic is-a relationships | The Sass documentation's rule of thumb: extends suit a relationship between semantic classes (`.error--serious` *is an* error), while mixins avoid cascade headaches for non-semantic collections of styles and are easier to configure later.

  • Why can a rule that uses `@extend` lose a cascade conflict its author expected it to win?
    Because the shared declarations are emitted where the extended rule is written, not where `@extend` appears. If `.alert` is defined early and a later rule of equal specificity sets the same property, the later rule wins even though `@extend .alert` sits at the very end of the file. A mixin's declarations land where the `@include` is, which is often what authors expect.
  • What happens when an `@extend` target does not exist?
    Sass reports an error: extends are mandatory by default, which catches typos and renamed selectors. Adding `!optional` (`@extend %card-base !optional;`) makes the extend do nothing when no rule contains the selector.
  • Does an `@extend` written in one Sass module affect every stylesheet in the build?
    Not under `@use`. An extension affects only rules in upstream modules, those the extending stylesheet loads with `@use` or `@forward` and what they load in turn. Under the deprecated `@import`, extensions were global and reached every imported and importing file, which is why large `@import` codebases saw surprising selectors.

@extend is adding your name to an existing guest list: you join the event where it is already being held, and you cannot join it from a different venue. A mixin is a photocopy of the programme handed to every guest, usable wherever they are.

  • @extend copies the declarations into the extending rule, just like a mixin.
  • Placeholder selectors appear in the output CSS with their % prefix.
  • @extend inside @media can extend any selector in the stylesheet.
  • The extended styles take effect at the position of the @extend rule.
  • @extend .card also extends the nested rule written as &__title inside .card.
  • @extend always beats mixins because it produces smaller downloads.