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;
}
Wildcard selectors allow you to select multiple matching elements. In CSS, three wildcard selectors exist i.e. $, ^, and * The * wildcard is known as the containing wildcard since it selects elements containing the set value. With the ^ wildcard, you get to select elements whose attribute value starts with the set ...
The asterisk (*) is known as the CSS universal selectors. It can be used to select any and all types of elements in an HTML page. The asterisk can also be followed by a selector while using to select a child object. This selector is useful when we want to select all the elements on the page.
Wildcard selector is used to select multiple elements simultaneously. It selects similar type of class name or attribute and use CSS property. * wildcard also known as containing wildcard.
The adjacent sibling combinator ( + ) separates two selectors and matches the second element only if it immediately follows the first element, and both are children of the same parent element .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With