DEV Community

Cover image for Set css style using html data attribute
MD ASHRAF
MD ASHRAF

Posted on

Set css style using html data attribute

Using attr() function

Here's the syntax:

element {
  property: attr(data-attribute-name);
}
Enter fullscreen mode Exit fullscreen mode

For example, if you have an HTML element like this:

<div data-color="#ff0000"></div>

You can access the data-color attribute in CSS like this:

div {
  background-color: attr(data-color);
}
Enter fullscreen mode Exit fullscreen mode

However, this will only work for certain properties like content, and not for properties like background-color.

If you want to use the data attribute value for styling purposes, you can use this way:

Solution 1:

style.css

a{
  background-color: attr(data-bg-color type(<color>)); /*add type(<color>) as it is, to tell browser that type of value is a type of color*/
  font-size: attr(data-font-size px)}
}
Enter fullscreen mode Exit fullscreen mode

.html

<a href="https://www.w3schools.com" data-font-size="30" data-bg-color="#ff0000">Visit W3Schools</a>
Enter fullscreen mode Exit fullscreen mode

Solution 2:

You can also use CSS custom properties (variables) to achieve this. For example:

<div style="--color: #ff0000;"></div>

div {
  background-color: var(--color);
}
Enter fullscreen mode Exit fullscreen mode

This way, you can dynamically set the value of the --color property and it will be used in the CSS.

Note: that the attr() function is not widely supported for all properties, and it's mainly used for the content property. For other properties, you may need to use other approaches like attribute selectors or custom.

Top comments (0)