CSS class selector wildcard

11,677

Use an attribute selector:

button [class*="button-"] {
  margin-right: 2rem;  
}

Example Here


From MDN:

[attr*=value] - Represents an element with an attribute name of attr and whose value contains at least one occurrence of string "value" as substring.

button [class*="button-"] {
  color: red;
}
<button>
    <span class="button-0">text</span>
    <span class="button-1">text</span>
    <span class="button-2">text</span>
</button>

As Chad points out, it is entirely possible that an element can contain a class such as this-is-my-button-class. In which case, that undesired element would be selected. In order to prevent this, you could use a combination of two selectors:

Example Here

button [class^="button-"],
button [class*=" button-"] {
  margin-right: 2rem;  
}

The selector button [class^="button-"] ensures that the element will be selected if it starts with button-. Since it's possible the element's first class doesn't start with button-, the selector [class*=" button-"] (note the whitespace), ensures that it will be selected.

Share:
11,677

Related videos on Youtube

intaglioman
Author by

intaglioman

Updated on September 15, 2022

Comments

  • intaglioman
    intaglioman over 1 year

    So I was wondering if there was a way to throw a wildcard into my CSS?

    I have several classes that are .button-0, .button-1, .button-2, .button-3, etc. within a button element. I want to get all the .button-* classes to define.

    Is it possible to do something like:

    button .button-[=*] {
      margin-right: 2rem;  
    }

  • intaglioman
    intaglioman about 9 years
    Thanks I will give that a try!
  • Chad
    Chad about 9 years
    That will work, but to start a selector with a string you should use the ^ selector, like button [class^="button-"].
  • Josh Crozier
    Josh Crozier about 9 years
    @Chad ..what if the element has multiple classes and button- isn't the first class? In that case ^ wouldn't work.
  • Chad
    Chad about 9 years
    @JoshCrozier but what if he has a class like this-is-my-button-class?
  • Chad
    Chad about 9 years
    @JoshCrozier You could hack it a bit, and do a double selector like: div[class^="button-"], div[class*=" button-"], making sure to grab the first one or one that has a space preceding it. (I'm playing devil's advocate here)
  • Chad
    Chad about 9 years
    Actually that's the CSS2 spec, and does not base off of a string, so if he wanted to be sure that it had a dash (like if a button was called <button class="btn btn-gray">, this solution wouldn't work.
  • BoltClock
    BoltClock about 9 years
    @Chad: That is the most foolproof answer.
  • Josh Crozier
    Josh Crozier about 9 years
    @Chad Thanks. I completely forgot about that option. Updated :)