DEV Community

Cover image for Can we assign css to dynamic Generated Classes? YES we can
Ahmed Zeno
Ahmed Zeno

Posted on

Can we assign css to dynamic Generated Classes? YES we can

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

Alt Text

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
}
Enter fullscreen mode Exit fullscreen mode
<div class="box-123"></div>
<span class="box-124"></span>
<article class="box-125"></article>
Enter fullscreen mode Exit fullscreen mode

Alt Text

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
}
Enter fullscreen mode Exit fullscreen mode
<div class="form-123"></div>
<span class="form-124"></span>
<article class="form-125"></article>
Enter fullscreen mode Exit fullscreen mode

Alt Text

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
}
Enter fullscreen mode Exit fullscreen mode
extra-class {
  background: blue !important;
}
Enter fullscreen mode Exit fullscreen mode

Alt Text

Alt Text

Top comments (4)

Collapse
 
marcellothearcane profile image
marcellothearcane

Why not just give it two classes? form form-123

Collapse
 
liqilinhub profile image
liqilinhub

when we finish the project, but find a problem ,we have to change all the style of 'form-*',this will be useful.

Collapse
 
alohci profile image
Nicholas Stimpson

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 an inform-xxx class, which your second option would otherwise do.

Collapse
 
jadzeino profile image
Ahmed Zeno

thats could also be handy , thanks for you note ('' ,)