Weird @extend side effects

Friends don’t let friends use @extend. I have this project that’s using Bootstrap. Instead of importing the CSS and expanding the styles with my own, I’m importing the Sass styles and compiling to a single CSS file. It was upon doing so that I noticed something strange. Bootstrap defines a button class like so (code…

Friends don’t let friends use @extend.

I have this project that’s using Bootstrap. Instead of importing the CSS and expanding the styles with my own, I’m importing the Sass styles and compiling to a single CSS file. It was upon doing so that I noticed something strange.

Bootstrap defines a button class like so (code snipped for brevity, because my focus is on the selectors):

.btn {
  // styles
}

Some of my own styles were using the Sass directive @extend for a form input button:

.search-form .search-submit {
  @extend .btn;
  @extend .btn-secondary;
}

Elsewhere, I had some link-specific styles that I wanted to make sure didn’t get applied to the .btn class:

a:not(.btn) {
  // styles
}

Once I compiled to CSS, however, I wasn’t seeing those link-specific styles being applied. Instead, this is what was output to my stylesheet:

a:not(.btn):not(.search-form .search-submit) {
  // styles
}

This was due to my use of @extend in on the submit button. So I copied Bootstrap’s button class into a mixin in my own stylesheet, and changed the button styles to this:

.search-form .search-submit {
  @include button;
  @include button-variant($secondary, $secondary);
}

Once I made that change, the output to my stylesheet was as I expected:

a:not(.btn) {
  // styles
}

Note: the button mixin is mine. The button-variant mixin already exists within Bootstrap’s code.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related