Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS class selector wildcard [duplicate]

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;  
}
like image 708
intaglioman Avatar asked Mar 02 '15 14:03

intaglioman


People also ask

Can you use wildcard in CSS selector?

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 ...

Why do we use * in CSS?

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.

What is the purpose of * wildcard in a selector?

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.

How do I target a sibling in CSS?

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 .


1 Answers

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.

like image 132
Josh Crozier Avatar answered Oct 12 '22 22:10

Josh Crozier