Sass - wildcard class name

Is it possible to have a wildcard class name?

for example, I have several divs .div-one , .div-two , .div-three , etc. Is there a way to use below in sass to select all divs with that name or is it best to give one class that covers all and unique classes on each?

.div-*{}

+16
source share
4 answers

In CSS, you can use an attribute selector with ^ :

div[class^="div-"] ==> Selects all div with the class attribute value starting with "div-"

Example:

 div { height: 20px; margin-bottom: 5px; border: 1px solid black; } div[class^="div-"] { border-color: red; } 
 <div class="div-one"></div> <div class="div-two"></div> <div class="other"></div> <div class="div-three"></div> 

Update

As @FreePender says, if the CSS class does not match the class in the attribute value, it does not work. Another solution is to use an attribute selector with * :

div[class*="div-"] ==> Selects all div with a class attribute value containing "div-".

That way, it will also correspond to a CSS class called nodiv-one , but this is not what usually happens.

 div { height: 20px; margin-bottom: 5px; border: 1px solid black; } div[class*="div-"] { border-color: red; } 
 <div class="div-one"></div> <div class="div-two"></div> <div class="other"></div> <div class="myclass div-three"></div> 

+35
source

A small remark, but I noticed that when embedding this rule in Sass you need to put an ampersand directly opposite the opening square bracket.

This does not work:

 .zoomed { & [class*=" aspect-"] { margin-bottom: $spacer * 4.0; } } 

But it is so:

 .zoomed { &[class*=" aspect-"] { margin-bottom: $spacer * 4.0; } } 

Pay attention to the position of the ampersand.

+5
source

You can use this method. Create a mixin:

 @mixin myDIV($name, $color, $color-hover) { .div-#{$name} { a { color: #{$color}; &:focus, &:hover { color: #{$color-hover}; } } } } 

Using:

 @include myDIV('one', $blue, $blue-hover); @include myDIV('two', $green, $green-hover); @include myDIV('three', $red, $red-hover); 

You can change the variables ($ blue) and css properties to suit your styles.

+4
source

The accepted answer is theoretical, but the last one is chrome today:

For CSS rule:

 [class^="div-"] 

markup

 class="div-something other-class" 

whereas:

 class="other-class div-something" 

does not match

_ (ツ) _ / ¯

0
source

All Articles