Get value of attribute in CSS

Inline CSS variables are almost as declarative as data attributes, and they are widely supported now, in contrast to the attr(). Check this out:

var elem = document.getElementById("demo");
var jsVar = elem.style.getPropertyValue("--my-var");
function next() {
  jsVar = jsVar % 5 + 1; // loop 1..5
  elem.style.setProperty("--my-var", jsVar);
}
.d1 {
  width: calc( var(--my-var) * 100px );
  background-color: orange;
}
.d2 {
  column-count: var(--my-var);
}
<button onclick="next()">Increase var</button>
<div id="demo" style="--my-var: 2">
  <div class="d1">CustomWidth</div>
  <div class="d2">custom columns number custom columns number custom columns number custom columns number custom columns number custom columns number custom columns number</div>
</div>

You need the attr CSS function:

div {
    width: attr(data-width);
}

The problem is that (as of 2021) it's not supported even by some of the major browsers (in my case Chrome):

enter image description here


You cant pass data attribute value directly in to css without pseudo type content. Rather you can do this way.. CHECK THIS FIDDLE

<div data-width="a"></div><br>
<div data-width="b"></div><br>
<div data-width="c"></div>

CSS

div[data-width="a"] {
    background-color: gray;
    height: 10px;
    width:70px;
}
div[data-width="b"] {
    background-color: gray;
    height: 10px;
    width:80px;
}
div[data-width="c"] {
    background-color: gray;
    height: 10px;
    width:90px;
}

Tags:

Html

Css