CSS class selector wildcard [duplicate]

2019-03-28 01:26发布

问题:

This question already has an answer here:

  • Is there a CSS selector by class prefix? 4 answers

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;  
}

回答1:

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.



回答2:

You can do like this

button[id|=button]{
    color:red;
}

All buttons whose id contain the word button will get affected. For example http://jsfiddle.net/czp28jpb/