CSS class selector wildcard
Use an attribute selector:
button [class*="button-"] {
margin-right: 2rem;
}
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:
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.
Related videos on Youtube
intaglioman
Updated on September 15, 2022Comments
-
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 abutton
element. I want to get all the.button-*
classes to define.Is it possible to do something like:
button .button-[=*] { margin-right: 2rem; }
-
intaglioman about 9 yearsThanks I will give that a try!
-
Chad about 9 yearsThat will work, but to start a selector with a string you should use the
^
selector, likebutton [class^="button-"]
. -
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 about 9 years@JoshCrozier but what if he has a class like
this-is-my-button-class
? -
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 about 9 yearsActually 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 about 9 years@Chad: That is the most foolproof answer.
-
Josh Crozier about 9 years@Chad Thanks. I completely forgot about that option. Updated :)