Cesar Rodriguez Cesar Rodriguez - 2 months ago 6
CSS Question

Can I Abbreviate input types in sass?

Writting some code in sass I found this situation:

input[type="text"]:focus {
border: 3px solid #AFDDFB;
transition: 100ms linear;
}


Now I need cover another input types like so:

input[type="text"]:focus, input[type="password"]:focus,
input[type="email"]:focus {
border: 3px solid #AFDDFB;
transition: 100ms linear;
}


I need some trick for speed up my writing, something like:

input[text, password, email]:focus {
//Dadada
}


Is there a way to do that using sass?

Answer

Predefined Properties
I personally go after shortness but it depends on the entire code if it fits to it or not. Up to you.

@mixin focus($types) {
    @each $type in $types {
        &[type=#{$type}]:focus {
            border:3px solid #AFDDFB;
            transition:100ms linear;
        }
    }
}
input {
    @include focus(text email password);
}

Demo Properties

@content;
And regarding Andy F's comment - here if you want a more flexible construct with @content;. Useful when you have more forms with different style. Not sure, if your mixins are in your own config file or in the same file with your code above. It's easier to change code in the same file instead of opening the config in case you have mixins/functions separated.

@mixin focus($types) {
    @each $type in $types {
        &[type=#{$type}]:focus {
            @content;
        }
    }
}
input {
    @include focus(text email password) {
        border:3px solid #AFDDFB;
        transition:100ms linear;
    }
}

Demo @content;

You're able to add even more input types to it like url, tel or number. Or even submit buttons if useful.