I have a class called .box-159
where the number changes every time the screen is refreshed. Is there a way to define this field (say background-color
) in the CSS?
Asked
Active
Viewed 2.7k times
12

Peter Mortensen
- 30,738
- 21
- 105
- 131

user5941451
- 121
- 1
- 1
- 4
-
Does CSS allow wildcards? I don't think so. You could refer to the element by something other than the class – jpaugh Feb 25 '16 at 22:03
-
are you asking to style the element differently based on the number at the end of the class? – Cruiser Feb 25 '16 at 22:09
2 Answers
35
Yes it is possible just by using CSS only.
Option #1 - Match by prefix value
- Use CSS Class selector
^="class"
which select all elements whose class is prefixed by "box-"
[class^="box-"] {
background: red;
height: 100px;
width: 100px;
margin: 10px 0;
display:block
}
<div class="box-159"></div>
<span class="box-147"></span>
<article class="box-76878"></article>
Option #2 - Match by contains at least one value
- Use another CSS class selector
*="class"
(equivalent to CSS attribute selector) which select all elements whose class contains at least one substring "box-".
[class*="box-"] {
background: red;
height: 100px;
width: 100px;
margin: 10px 0;
display:block
}
<div class="box-159"></div>
<span class="box-147"></span>
<article class="box-76878"></article>

dippas
- 58,591
- 15
- 114
- 126
4
You can add an additional class, like so, then both those elements will have the class' CSS attributes:
.box-class {
background-color: red;
width: 100px;
height: 100px;
margin-bottom: 20px;
}
<div class="box-class box-4"></div>
<div class="box-class box-159"></div>

Clemens Himmer
- 1,340
- 2
- 13
- 26
-
1Another class is not necessary, this can be done with a CSS selector alone. – Adam Konieska Feb 25 '16 at 22:05
-
1I just noticed, well it is a non-efficiant, working solution at least :) – Clemens Himmer Feb 25 '16 at 22:06
-
2I prefer this solution. Attribute selectors, especially using partial string matching, will always be slower than a simple class selector like this. – Heretic Monkey Feb 25 '16 at 22:14