Match all elements having class name starting with a specific string

Css

Css Problem Overview


Is it possible to use a "wildcard" for elements having a class name starting with a specific string in CSS3?

Example:

<div class="myclass-one"></div>
<div class="myclass-two"></div>
<div class="myclass-three"></div>

and then magically set all the above divs to red in one go:

.myclass* { color: #f00; }

Css Solutions


Solution 1 - Css

The following should do the trick:

div[class^='myclass'], div[class*=' myclass']{
    color: #F00;
}

Edit: Added wildcard (*) as suggested by David

Solution 2 - Css

It's not a direct answer to the question, however I would suggest in most cases to simply set multiple classes to each element:

<div class="myclass one"></div>
<div class="myclass two"></div>
<div class="myclass three"></div>

In this way you can set rules for all myclass elements and then more specific rules for one, two and three.

.myclass { color: #f00; }

.two { font-weight: bold; }

etc.

Solution 3 - Css

You can easily add multiple classes to divs... So:

<div class="myclass myclass-one"></div>
<div class="myclass myclass-two"></div>
<div class="myclass myclass-three"></div>

Then in the CSS call to the share class to apply the same styles:

.myclass {...}

And you can still use your other classes like this:

.myclass-three {...}

Or if you want to be more specific in the CSS like this:

.myclass.myclass-three {...}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjchwebdevView Question on Stackoverflow
Solution 1 - CssKoen.View Answer on Stackoverflow
Solution 2 - CssJames MontagneView Answer on Stackoverflow
Solution 3 - CssAndyView Answer on Stackoverflow