Search code examples
csssass

Inherit sass modifier in extending classes


I have a base class for all buttons that looks like

.btn {
    height: var(--btn-height-base);
    padding: 0 10px;

    font-size: 16px;
    line-height: 20px;
    font-weight: 500;
}

Button designs extend this class like this:

.btn-primary {
    @extend .btn;
    background: var(--color-brand);
    color: var(--txt-white);

    &:active,
    &:hover {
        background: var(--color-brand-active);
        color: var(--txt-white);
    }
}

I want to add a modifier to all designs called --icon that applies gap: 6px;. It would then be used like btn-primary--icon or btn-border--icon. Is this possible without repeating this modifier in all my button designs? I have tried adding

&--icon {
    @extend .btn;
    gap: 6px;
}

to my .btn class, but that only seems to apply to .btn--icon.


Solution

  • No, it's not possible, as explained in the docs:

    Extends are resolved after the rest of your stylesheet is compiled. In particular, it happens after parent selectors are resolved. This means that if you @extend .error, it won’t affect the inner selector in .error { &__icon { ... } }. It also means that parent selectors in SassScript can’t see the results of extend.