DEV Community

Cover image for Using attr() with types
Alvaro Montoro
Alvaro Montoro Subscriber

Posted on • Originally published at alvaromontoro.com

Using attr() with types

Chrome supports the type notation for attr(). This allows to specify the type of an attribute once it is read:

<style>
div {
  color: attr(data-color type(<color>));
}
</style>

<div data-color="red">I am red</div>
Enter fullscreen mode Exit fullscreen mode

The (huge) benefit of this is that attributes can be used with any CSS property in any element, instead of just in the content in pseudo-elements.

The type() function takes a as its argument specifying what data type should be used when parsing the attribute. The <syntax> can be:

  • <angle>
  • <color>
  • <image>
  • <integer>
  • <length>
  • <length-percentage>
  • <number>
  • <percentage>
  • <resolution>
  • <string>
  • <time>
  • <transform-function>

Basically, the same types that can be used in the syntax property of an @property rule, except for the <url> one, due to security reasons.

Chrome implemented this change earlier this year, and it went under my radar. It will still be a while until it’s widely supported, but I’m glad it is there. I’ve been waiting for this feature for a really long time.

Looking forward to seeing this feature in more browsers. It will make development cleaner, and remove the need for the "let's set this as a CSS variable inline" hacky solution that we have right now.

More information about attr() and types on MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/attr

Top comments (0)