Read more

SASS: Reusing styles from other files

Dominik Schöler
March 28, 2023Software engineer at makandra GmbH

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
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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.

Posted by Dominik Schöler to makandra dev (2023-03-28 10:19)