Sass @extend base/default without also extending p

2019-02-05 09:33发布

问题:

I know I can @extend .foo:hover, but is there a way to @extend the .foobar base/default properties without also extending the definitions for pseudo-classes like :hover, :active, etc?

For example, how would I change the following such that .foobar extends only .foo's default state?

.foo {
    & {
         color:blue;
    }
    &:hover {
         background-color: black;
    }
}

.foobar {
     @extend .foo;
     &:hover {
          //As is, I have to override. Any better way?
          background-color: transparent;
     }
}

(If there is no way to do this with Sass, is there a preferred way to achieve the same effect?)

回答1:

You have to rewrite your selectors in such a way that you only extend exactly the part you want:

%foo {
    color:blue;
}

.foo {
    @extend %foo;

    &:hover {
         background-color: black;
    }
}

.foobar {
    @extend %foo;

    &:hover {
         background-color: transparent;
    }
}

However, depending on how you are going to be extending/reusing your .foo class, the new @content directive might be the better way to go.

@mixin foo {
    color: blue;

    &:hover {
        @content;
    }
}

.foo {
    @include foo {
        background-color: black;
    }
}

.foobar {
    @include foo {
        background-color: transparent;
    }
}