Can we specify custom data attribute values in CSS?

Nitesh picture Nitesh · Apr 12, 2016 · Viewed 8.8k times · Source

On elements I can specify the data attributes as, e.g.

<div data-widget-type="MyWidgetType1" data-property1="20" data-property2="test">
...
</div>

I want to capture these in a class e.g.

.MyClass1 {
 data-widget-type:"MyWidgetType1";
 data-property1:"20";
 data-property2:"test";
}

<div class="MyClass1">
...
</div>

Is there a way to specify data attribute values in CSS?

Answer

BoltClock picture BoltClock · Apr 12, 2016

CSS is not HTML. You cannot set or change the value of an HTML attribute using CSS.

Besides, why would you do this? HTML and CSS exist because of separation of concerns. HTML is for content and CSS is for presentation. Specifying data attributes in CSS is no different to specifying presentational attributes in HTML.

If you're trying to assign metadata to a class name which then applies to all elements with that class name, that's (again) completely outside of the purview of CSS, and simply not possible in HTML. The only way to assign metadata to an element is to specify it as an attribute on that element. (You can move the attribute declarations to a script if you don't want to specify the attributes on every instance of that class within the markup, but at the end of the day the script still has to populate each element's dataset with those values. Depending on your needs, though, this may be sufficient.)