The old CSS attr() with new features
The CSS attr() function retrieves a value from an HTML element’s attribute. Firefox added support for it two decades ago, so it’s rather not a new thing. I can’t tell you how many times I had an incredible use case for it, just to be reminded a second later that its use is limited to the content property. Here is an example.
<article data-category="Technology">...</article>
article::before {
content: "In category: " attr(data-category);
}
Baseline: attr() (content only) is widely available
- Google Chrome
2 2009.05.21
- Microsoft Edge
12 2015.07.29
- Firefox
1 2004.11.09
- Safari
3.1 2008.03.18
The new attr() function
I’m not sure if you noticed, but in the last few years all the impossible-to-implement CSS features all of a sudden became possible. The CSS Values and Units Module Level 5 redefines the attr() function, opens its functionality to all properties, allows us to exchange a value between the markup and stylesheet that is not only limited to strings, and also accepts a fallback.
<article data-background="salmon">...</article>
article {
background-color: attr(data-background type(<color>), lime);
}
Baseline: attr() has limited availability
- Google Chrome
Not supported Not supported
- Microsoft Edge
Not supported Not supported
- Firefox
Not supported Not supported
- Safari
Not supported Not supported
This update to the spec is backward compatible, with only two exceptions defined on MDN. The value can be parsed into all CSS types with the exception of URL to avoid potential security threats. Of course, we can detect browser support for this feature using the CSS supports API.
@supports (x: attr(x type(*))) {
/* 👍 */
}
@supports not (x: attr(x type(*))) {
/* 👎 */
}
if (CSS.supports("x: attr(x type(*))")) {
/* 👍 */
}
if (!CSS.supports("x: attr(x type(*))")) {
/* 👎 */
}
Now the attr() works how I always wanted it to! I miss writing about CSS. I miss CSS. Expect more of it. Stay curious, geeks 👋
Have you found any fun experiments or ways to incorporate this? I'm having a hard time coming up with anything crazy, but I am enjoying the pipeline of new features coming like scroll animations. Kinda crazy that scroll spy/popovers and modal/dialogs are finally becoming html standards