This question already has an answer here:
-
Is there a CSS selector by class prefix?
4 answers
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?
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>
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>