SASS apply to only one style

2020-05-08 07:45发布

问题:

Is there a way to have something like this:

.class1, .class2 {
    background: green;

    :not(.class1) {
        //Only apply to .class2
        background: red;
    }
}

Compile to

.class1, .class2 { background: green; }
.class2 { background: red; }

Im trying not to have .class2 have its own separate style somewhere else.

回答1:

No, it is only possible to be inclusive with Sass using nesting, not exclusive. Have you looked at the @extend directive?

%common-styles {
    border: 1px solid;
}

.class1 {
    @extend %common-styles;
    background: green;
}

.class2 {
    @extend %common-styles;
    background: red;
}

Would compile to this (not sure on exact order here, don't have Sass available at the moment):

.class1 { background: green }
.class2 { background: red }
.class1, .class2 { border: 1px solid }

Obviously not the solution you are looking for, but it is the approach you would typically take with Sass. Is there a reason you can't keep the unique .class2 styling with the rest of the styles?

.class1, .class2 {
    background: green;
}

.class2 {
    background: red;
}

Alternately, you could do this:

.class2 {
    background: red !important;

    &, .class1 {
        background: green;
    }
}


标签: sass