tezvyn:

Sass @mixin versus @extend

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

how Sass features shape output.

OUTLINE

@mixin copies declarations into each caller, accepts arguments, and can duplicate code; @extend groups selectors sharing one rule via a comma list, reducing duplication but coupling selectors.

WHAT THIS TESTS This checks deeper Sass knowledge: not just what mixins and extends do, but how each affects the generated CSS, which is where the real trade-off lives. Senior front-end engineers reason about output, not just source.

A GOOD ANSWER COVERS A mixin is a reusable block of declarations you pull in with include, and it can accept arguments and default values, making it ideal for parameterized or dynamic styles like a button variant that takes a color, or a responsive helper that takes a breakpoint. Its impact on output is duplication: the declarations are copied into every caller, so heavy reuse can bloat the CSS. @extend makes one selector inherit all the styles of another by adding the inheriting selector to the original rule's selector list as a comma-separated group, so the shared declarations appear only once. That keeps output smaller for identical, static shared styles, but it cannot take arguments, it couples selectors together, and the grouping can produce unexpected, far-reaching selector lists, and it does not extend across separate media query blocks. Use a mixin when you need parameters or dynamic values; use @extend for static, identical style sharing where you want to avoid duplication, often via placeholder selectors.

COMMON WRONG ANSWERS Saying they are equivalent. Believing @extend always produces smaller and better CSS, ignoring its selector-grouping surprises and media-query limitation. Trying to pass arguments to @extend. Overusing @extend and creating tangled selector groups that hurt readability and caching.

LIKELY FOLLOW-UPS Why does @extend not work across media queries? What is a placeholder selector and why pair it with @extend? When does mixin duplication actually matter with gzip? How do you decide between them?

ONE CONCRETE EXAMPLE For a button that needs different background colors, use a mixin taking a color argument, accepting that each button variant duplicates the declarations. For a shared message base where several alert types need identical padding and border styles, use @extend with a placeholder so all the alert selectors are grouped into one rule and the shared declarations are written once.

Read the original → sass-lang.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.