8

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;  
}
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
intaglioman
  • 167
  • 1
  • 2
  • 8

2 Answers2

13

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.

Community
  • 1
  • 1
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • That will work, but to start a selector with a string you should use the `^` selector, like `button [class^="button-"]`. – Chad Mar 02 '15 at 14:57
  • @Chad ..what if the element has [multiple classes](http://jsfiddle.net/L74fvd0a/) and `button-` isn't the first class? In that case `^` wouldn't work. – Josh Crozier Mar 02 '15 at 14:57
  • @JoshCrozier but what if he has a class like `this-is-my-button-class`? – Chad Mar 02 '15 at 14:59
  • 1
    @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 Mar 02 '15 at 15:06
  • 1
    @Chad: That is the most foolproof answer. – BoltClock Mar 02 '15 at 15:12
  • @Chad Thanks. I completely forgot about that option. Updated :) – Josh Crozier Mar 02 '15 at 15:17
0

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/

YourFriend
  • 434
  • 4
  • 7
  • 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 ` – Chad Mar 02 '15 at 15:11