Ashish Joshi Ashish Joshi - 4 months ago 7
HTML Question

dynamically provide values to css

I am trying to set color of div dynamically.

To give an overview of issue, let's check below tings.

<!doctype html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="shape" id="shape1"></div>
<div class="shape" id="shape2"></div>
<div class="shape" id="shape3"></div>
</body>
</html>


Below is the css am using..

.shape {
display: inline-block;
width: 200px;
height: 200px;
background: #dfd;
margin: 20px;
}


is it possible that I can give
class="shape-fdd"
in html then it show light red color, if i give
class="shape-dfd"
then it show light green color?

I have just looked into LESS for the same but i don't know if it can provide this feature.

I don't look for jQuery solutions for this. Only CSS or with LESS or SASS if possible.

Any help is appreciated.

Answer

Just a quick note for info. It is not yet possible in css3 (only for content attribute right now) but maybe soon:

<!doctype html>
<head>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="shape" id="shape1" data-color="#fdd"></div>
    <div class="shape" id="shape2" data-color="#fdd"></div>
    <div class="shape" id="shape3" data-color="#fdd"></div>
</body>
</html>


.shape {
  display: inline-block;
  width: 200px;
  height: 200px;
  background: attr(data-color);
  margin: 20px;
}

Can check on CSS - Add Color with a data attribute - attr(data-color color)

Comments