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>
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 (1)
Back when
--custom-properties
released it was kinda weird that there wasn't a nicer way of setting them via HTML than usingstyle
; I believe some basic version ofattr()
had already been discussed at the time, but was mostly dead for many years.Now that
attr()
is making it into browsers, that's probably the best way to do it; have custom properties be CSS only by default, but allow CSS authors to expose it to HTML viaattr()
when needed. Of course not in a security sense, asstyle
can still be used, but to have the ergonomics of it guide HTML authors to use the right interface with CSS.JS-less custom elements also become a lot more viable like this; just thinking
<vertical-separator height="2em">
,<grid-box gap="2em">
, etc.