Sass - Class name wildcard

The accepted answer is cool in theory, but in the latest chrome as of today:

For the CSS rule:

[class^="div-"]

the markup

class="div-something other-class"

matches, whereas:

class="other-class div-something"

does not match

¯\_(ツ)_/¯


Small point but I noticed that when nesting this rule in Sass, you need to put the ampersand right against the opening square bracket.

This doesn't work:

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

But this does:

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

Note the position of the ampersand.


In CSS you can use the attribute selector with ^:

div[class^="div-"] ==> Selects all div with a 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 isn't the one in the attribute's value, it doesn't work. Another solution is to use the attribute selector with *:

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

This way it would also match a CSS class named nodiv-one for example, but it's not something that happens normally.

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>

Tags:

Sass