I have a class called .form-123 where the number changes every time the screen is refreshed. Is there a way to define this field (say background-color or margin) in the CSS?
Yes it is possible just by using CSS only, and there is 3 ways to do that
Option #1 - Match by prefix value
Use CSS Class selector ^="class" which select all elements whose class is prefixed by "form-"
example
[class^="form-"] { background: red; height: 100px; width: 100px; margin: 10px 0; display:block }
<div class="box-123"></div> <span class="box-124"></span> <article class="box-125"></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 "form-".
[class*="form-"] { background: red; height: 100px; width: 100px; margin: 10px 0; display:block }
<div class="form-123"></div> <span class="form-124"></span> <article class="form-125"></article>
Option #3 - Add an additional class to the element, then both those elements will have the class' CSS attributes:
.form-123 { background: blue; height: 100px; width: 100px; margin: 10px 0; display:block }
extra-class { background: blue !important; }
Top comments (4)
Why not just give it two classes?
form form-123
when we finish the project, but find a problem ,we have to change all the style of 'form-*',this will be useful.
I'd combine option 1 and option 2 (slightly modified) as
[class^="form-"],[class*=" form-"] { ... }
so the
form-xxx
class can appear anywhere in a list of classes, and at the same time not match aninform-xxx
class, which your second option would otherwise do.thats could also be handy , thanks for you note ('' ,)