SCSS Variables as @extend class

2019-02-12 12:10发布

问题:

My idea is that I would like to write silent classes for input[type=text], input[type="password"] and input[type=submit]. I would then @extend them in a mixin by passing hem through as a variable.

My parser is throwing this error;

Syntax error: Invalid CSS after "   @extend ": expected selector_sequence, was "$type;"

Here is my code;

%text {
    (text styling)
}

%password {
    @extend %text;
}

%submit {
    padding: .5em;
    background-color: $button-color;
    border: none;
    cursor: pointer;
    color: white;
    border: 1px solid darken($button-color, 20%);
    &:hover {
        @include transition;
        background-color: darken($button-color, 10%);
    }
}

@mixin input($type) {
    margin-bottom: 1.5em;
    margin-left: 0;
    outline: none;
    @extend $type;
}

Any help would be appreciated

回答1:

try using variables interpolation

@extend #{$type};

Further information on SASS Reference



回答2:

While Fabrizio's answer is formally correct, consider not going that way.

There's a great rule in programming of any kind: "keep it simple, stupid!" aka KISS.

Though SASS provides such advanced facilities as extends and mixins, it doesn't mean that you should use them as much as possible. Don't make your code complicated when you don't have to!

This code does exactly what you want: applying styles to input[...] selectors:

input {
    margin-bottom: 1.5em;
    margin-left: 0;
    outline: none;
}

input[type=text], input[type=password] {
    font-family: Verdana; // Text styles
} 

input[type=submit]  {
    padding: .5em;
    background-color: $button-color;
    border: none;
    cursor: pointer;
    color: white;
    border: 1px solid darken($button-color, 20%);
    &:hover {
        @include transition;
        background-color: darken($button-color, 10%);
    }
}

If you want to apply styles to custom classes/ids, consider this approach:

/////////////////
// Silent classes
/////////////////

%input {
    margin-bottom: 1.5em;
    margin-left: 0;
    outline: none;
}

%text {
    @extend %input;
    font-family: Verdana;
}

%password {
    @extend %text;
}

%submit {
    @extend %input;
    padding: .5em;
    background-color: $button-color;
    border: none;
    cursor: pointer;
    color: white;
    border: 1px solid darken($button-color, 20%);
    &:hover {
        @include transition;
        background-color: darken($button-color, 10%);
    }
}



///////////////////////////
// Applying silent classes:
///////////////////////////

.some .weirdly .nested input[type=text] {
    @extend %text;
}

.password {
    @extend %password;
}

#the-submit-button {
    @extend %submit;
}

Demo: http://sassbin.com/gist/5956909/



标签: css sass