Search code examples
csssasspseudo-class

Use pseudo classes with variables in Sass


I've been unable to wrap my head around how to execute this idea I have using pseudo classes with variables in Sass.

My case

I'm creating a form which has several input[type=text]fields and an input[type=email] field and for those fields I want to create the normal, hover and focus states.

So the compiled CSS would look like this:

input[type=text],
input[type=email] { background:#eee; }

input[type=text]:hover,
input[type=email]:hover { background:#aaa; }

input[type=text]:focus,
input[type=email]:focus { background:#666; }

So I created this variable:

$inputs: "input[type=text], input[type=email]";

And for the normal state I have:

#{$inputs} { background:#eee; }

So in my naive mind I thought that doing #{$inputs}:hover { background:#aaa; } would work... but it doesn't, of course, Sass can't just "guess" what I want just like that :p

Which is why I'm here.

Question

Any suggestions on how I can use pseudo classes on variables like I describe above?

Any help and guidance would be greatly appreciated.

Thanks.


Solution

  • I'd go for this:

    input[type=text],
    input[type=email]
    {
       background:#eee;
    
       &:hover
       {
           background:#aaa;
       }
    
       &:focus
       {
           background:#666;
       }
    
    }
    

    Here is demo fiddle: http://jsfiddle.net/ApxSB/

    As @ricardozea said, you may also put the selectors in a variable like this:

    $inputs: "input[type=text], input[type=email]";
    
    #{$inputs}
    {
    }
    

    Demo here: http://jsfiddle.net/NicoO/ApxSB/1/