SASS: Reusing styles from other files

Posted . Visible to the public.

SASS has an @extend keyword Show archive.org snapshot to inherit styles.

.alert
  color: red
  
  &.-framed
    border: 1px solid red
    padding: 5px
    
  &.-homepage
    @extend .-framed
    border-width: 5px

When compiling, SASS will simply join the selectors. Note how .-homepage is written where .-framed was defined:

...
.alert.-framed, .alert.-homepage {
  border: 1px solid red;
  padding: 5px;
}
.alert.-homepage {
  border-width: 5px;
}

Warning

Unfortunately, this does not work properly in a multi-file environment, where a bundler like Webpack or esbuild requires individual files. While you could @import (or @use) another file and then @extend of its definitions, each import would add the imported styles to the output again.

If you want to use @extend with multiple files, you need to stop concatenating files using the import and require of your bundler. Instead you must concatenate files using Sass' @import statement.

Dominik Schöler
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2023-03-28 08:19)