Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a dynamic class be styled using CSS? [duplicate]

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?

like image 855
user5941451 Avatar asked Feb 25 '16 22:02

user5941451


People also ask

How do I change a dynamic class in CSS?

In this article, we will see how to dynamically create a CSS class and apply to the element dynamically using JavaScript. To do that, first we create a class and assign it to HTML elements on which we want to apply CSS property. We can use className and classList property in JavaScript.

Can we change CSS dynamically?

color = "red"; you can apply the style change dynamically. Below is a function that turns an element's colour to red when you pass it the element's id . You could also use setAttribute(key, value) to set a style on an element. For example, you could set the colour of an element to red by calling element.

Which method is used to add a CSS class dynamically?

You can use Javascript for adding a class: setAttribute and className both method are used to set class (class attribute), these method are not used to adding another class with existing one. simply using className= will clear te other classes.

Can an element have 2 CSS classes?

HTML elements can be assigned multiple classes by listing the classes in the class attribute, with a blank space to separate them.


2 Answers

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>
like image 155
dippas Avatar answered Nov 09 '22 01:11

dippas


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>
like image 45
Clemens Himmer Avatar answered Nov 08 '22 23:11

Clemens Himmer