Repository navigation
Description
Description
The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned. (MDN)
Specification
CSS Values and Units Module Level 5
# attr-notation
Open Issues
- [css-values] Security concerns regarding attr() w3c/csswg-drafts#5092
- [css-values] attr()'s url type seems wrong w3c/csswg-drafts#5079
attr()support extended capabilities (Interop 2023) #86 (not open, but a related issue from Interop 2023)
Tests
The below list of tests was generated using wpt-find (wpt-find -mlc 'attr(')
- /largest-contentful-paint/observe-css-generated-text.html
- /css/css-conditional/at-supports-namespace-001.html
- /css/css-content/attr-case-sensitivity-001.html
- /css/css-content/attr-case-sensitivity-003.html
- /css/css-content/attr-case-sensitivity-002.html
- /css/css-gcpm/string-set-012.html
- /css/css-align/self-alignment/self-align-safe-unsafe-flex-003.html
- /css/css-align/self-alignment/self-align-safe-unsafe-flex-002.html
- /css/css-align/self-alignment/self-align-safe-unsafe-grid-002.html
- /css/css-align/self-alignment/self-align-safe-unsafe-grid-003.html
- /css/css-align/self-alignment/self-align-safe-unsafe-grid-001.html
- /css/css-align/self-alignment/self-align-safe-unsafe-flex-001.html
- /css/css-variables/variable-generated-content-dynamic-001.html
- /css/cssom/serialize-values.html
- /css/cssom/css-style-attr-decl-block.html
- /css/css-values/attr-in-max.html
- /css/css-values/attr-color-valid.html
- /css/css-values/attr-invalid-type-008.html
- /css/css-values/attr-length-valid-zero-nofallback.html
- /css/css-values/attr-color-invalid-cast.html
- /css/css-values/attr-length-valid.html
- /css/css-values/attr-invalid-type-002.html
- /css/css-values/attr-color-invalid-fallback.html
- /css/css-values/attr-length-valid-zero.html
- /css/css-values/attr-px-invalid-fallback.html
- /css/css-values/attr-px-invalid-cast.html
- /css/css-values/attr-invalid-type-001.html
- /css/css-values/attr-length-invalid-cast.html
- /css/css-values/attr-px-valid.html
- /css/css-values/calc-rgb-percent-001.html
- /css/css-values/attr-length-invalid-fallback.html
- /css/CSS2/generated-content/content-attr-case-001.html
- /html/semantics/embedded-content/the-img-element/sizes/support/sizes-iframed.sub.html
- /resource-timing/content-type.html
Current Implementations
- Blink
- Gecko
- WebKit
Standards Positions
- Gecko/Mozilla
- Chromium/Blink
Browser bug reports
- Chromium
- https://bugs.chromium.org/p/chromium/issues/detail?id=1486443
- https://bugs.chromium.org/p/chromium/issues/detail?id=246571
- https://bugs.chromium.org/p/chromium/issues/detail?id=1082477
- https://bugs.chromium.org/p/chromium/issues/detail?id=1081995
- Gecko
- https://bugzilla.mozilla.org/show_bug.cgi?id=435426
- https://bugzilla.mozilla.org/show_bug.cgi?id=1481150
- https://bugzilla.mozilla.org/show_bug.cgi?id=1854104
- https://bugzilla.mozilla.org/show_bug.cgi?id=1369329
- WebKit
- https://bugs.webkit.org/show_bug.cgi?id=25851
- https://bugs.webkit.org/show_bug.cgi?id=26609
- https://bugs.webkit.org/show_bug.cgi?id=182343
Developer discussions
Some posts in support of attr():
X/Twitter
- https://x.com/LukyVJ/status/1377917512638201858
- https://x.com/chrisshank23/status/1704618645262041304
- https://x.com/shshaw/status/1150852516264980480
- https://x.com/CanadaHonk/status/1694111906158510220
- https://x.com/FWeinb/status/367748678737727489
- https://x.com/superissarah/status/1054939204038225920
- https://x.com/cramforce/status/654157266761846784
- https://x.com/codepo8/status/359357417026359297
- https://x.com/LeaVerou/status/591859793528233984
- https://x.com/pawelgrzybek/status/1548234308107636736
- https://x.com/calebwilliams12/status/1448325875750121478
- https://x.com/pbakaus/status/1155704562080083968
- https://x.com/blvdmitry/status/1303019591501852674
- https://x.com/rxgx/status/763867149320409088
StackOverflow
- https://stackoverflow.com/questions/18408488/setting-width-with-css-attr
- https://stackoverflow.com/questions/20490704/combine-calc-with-attr-in-css
- https://stackoverflow.com/questions/64476303/adding-attr-to-css
- https://stackoverflow.com/questions/42932294/css-attr-concatenation-with-url-path
- https://stackoverflow.com/questions/45194482/setting-width-with-css-attr
- https://stackoverflow.com/questions/35687762/using-css-attr-function-to-rotate-an-element
- https://stackoverflow.com/questions/48662218/css-attr-for-integers-what-is-a-good-way-to-solve-this
- https://stackoverflow.com/questions/48459561/attr-not-working
- https://stackoverflow.com/questions/8769786/css3s-attr-doesnt-work-in-major-browsers
If you search X/Twitter for "CSS attr" you will see plenty of posts from people excited about and/or curious about the future features of CSS attr(). You'd also see many posts echoing one opinion calling the attr() useless, especially in comparison to CSS custom properties.
I'd like to disagree with that sentiment, but… he's right. As the attr() function stands today, attr() is really only useful when trying to pull plain text from attributes to display using a pseudo-element.
It's mostly useless, but it doesn't have to be.
With these newer features, attr() would be exceedingly useful, not taking the place of CSS custom properties by any means but rather bridging the gap between markup values and CSS values. This would stand as a very productive separation of concerns.
Polls & Surveys
No response
Existing Usage
No response
Workarounds
The primary workaround for this is to use CSS custom properties, but this has several drawbacks and only lives in the markup in the form of inline styles. One of the greatest advantages of attr() is the ability to utilize the values set on the markup.
To achieve this with CSS custom properties, one would need to apply those values twice, once to the attributes for actual markup functionality and again as a CSS custom property for CSS usage. Example:
<!-- tightly coupled redundancies in the attributes vs. inline styles -->
<progress min="0" max="100" value="50" style="--min: 0; --max: 100; --value: 50;"></progress>
<style>
progress {
--percentage: calc((var(--value) - var(--min)) / (var(--max) - var(--min)) * 100%);
background: linear-gradient(to right, green var(--percentage), white var(--percentage));
}
</style>With attr(), we can achieve this more concisely, using attribute values directly:
<!-- here, the styles will inherit from the attributes dynamically, so no need to set the explicit values twice -->
<progress min="0" max="100" value="50"></progress>
<style>
progress {
/* I'm using `attr()` directly in this calculation, but these values could also be abstracted to CSS custom properties for ease of reuse */
--percentage: calc((attr(value number) - attr(min number)) / (attr(max number) - attr(min number)) * 100%);
background: linear-gradient(to right, green var(--percentage), white var(--percentage));
}
</style>Accessibility Impact
Tightly coupled code can lead to inconsistencies due to human/developer-error when updates are made. The DRY coding principle would reasonably apply here.
Privacy Impact
This issue focuses on security concerns using attr(), but there are already good ideas re how to circumvent those issues, the primary of which would be whitelisting: w3c/csswg-drafts#5092
Other
No response
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
webstrand commentedon Oct 4, 2023
I like to use
display: gridfor<table>markup. Being able to write generic css that handles most of the built-in table attributes would be nice, e.g.rowspancolspan...thebabydino commentedon Oct 4, 2023
Here's another use case: images with a spaced out gradient
borderthat looks extracted from the image.The markup for an image would be just
Then in the CSS, this would do the trick for the image with the spaced out "gradient" (actually very blurred) border:
No browser currently supports this and it's not just because of
attr().src()doesn't seem to be in any browser at the moment, whilefilter()is only supported in Safari (has been supported there for over 8 years at this point, but no other browser followed).The current cross-browser solution feels needlessly complicated.
First, when I generate the HTML, add a
--urlcustom property that uses the same image url from thesrcattribute.:Then in the CSS, I need all of this:
And this doesn't even include the
-webkit--prefixed version formask, which is still needed at this point (live demo).I'm intrigued! This looks very good in theory and I'd love to be able to use something like this for inputs! For example, for
input[type=range], this would eliminate the need for JS as we wouldn't need to rely on a JS-updated custom property for the value, like I'm doing in this demo.But one thing that confuses me is that I don't see the
valueattribute for such aninputchanging in DevTools as I drag the thumb. The actual value (that I update the--valcustom property with) does change, but not the number value in thevalueattribute. So wouldattr(value)actually work, or would it just be always the same value set initially in thevalueattribute?If
attr(value)could work incalc()and could get updated on dragging the thumb, that would be wonderful. Because I currently use the--valattribute to compute quite a few things, for example the position of a tooltip value display and the number value shown in that tooltip. And since--valcan only be updated via JS, no JS means no tooltip value display.brandonmcconnell commentedon Oct 4, 2023
@thebabydino Solid feedback all around. Examples like that greatly help to express this feature like this. Thank you!!
Re the
valueattribute updating, I've run into that as well a number if times and have a couple other proposals to address that—[css-values-5]
value()functionThis proposal introduces a CSS function for incorporating the live value of an input, exactly as you've put it here
[css-properties-values-api] add support for scope-global variables
This proposal introduces a completely new way to work with CSS custom properties — globally.
(expand/collapse explainer)
Hypothetically, you could use
@propertyto set up a custom property with a newglobaloption on its@propertyconfig set totrue. When the custom property is set up this way, it only ever has one value — that with the highest specificity. This way, we can set global values using states such as a checkbox or an input value and access it anywhere else in that scope.For example, you could create a dark mode toggle checkbox somewhere on the page, and without needing to resort to some top-level
:has()(not inherently bad, but an alternative), you could have that checkbox'scheckedstate update the global value naturally, like this:A feature like this would be essential for exposing attributes as well as the
valueproperty of descendant elements that cannot otherwise expose them upwards. I'm considering this feature a dependency of my othervalue()proposal.I would certainly appreciate any support you'd show to either of those proposals as well. Thank you 🙂
OnurGumus commentedon Oct 4, 2023
In addition I would add, inline styles aren't very good for security and CSP perspective.
webstrand commentedon Oct 4, 2023
@thebabydino
This was my first thought, too. Range is a pain to style, currently: https://codepen.io/webstrand/pen/bGLXdPR
Traditionally,
<input>elements don't update their attribute when their value property changes. Changing this behavior would be a breaking change as there's quite a lot of things that reuseinputEl.getAttribute("value")to restore fields to their initial state. For instance<button type="reset">looks at the attribute value to determine what to reset to.I'm not sure I'd be a fan of adding special cases for
attr(value)though.brandonmcconnell commentedon Oct 4, 2023
@webstrand I agree; I don't think we should introduce any special cases using
attr()to retrieve dynamic values like the livevalueprop of an input.If you're interested, take a peek at the other two proposals I mentioned, namely this one: [css-values-5]
value()functionjacobrask commentedon Oct 5, 2023
Another concrete example, an icon component that should be sized in
rems to scale with the text, and also usemask-imageto allow it to inherit the text color, so dual potential usage ofattrin one class. Currently we do something like thisbrandonmcconnell commentedon Oct 5, 2023
@jacobrask Great example. I've done something similar for custom progress bars:
CodePen demo
[-]`attr()` support extended capabilities[/-][+][css-values-5] `attr()` support extended capabilities[/+]bkardell commentedon Feb 1, 2024
Thank you for proposing
attr()support extended capabilities for inclusion in Interop 2024.We wanted to let you know that this proposal was not selected to be part of Interop this year.
As of the deadline, the specifications for
attr()support extended capabilities were not yet complete enough to allow interoperable implementations. To make progress on this area in the future, it will first be necessary to ensure that the feature has a clear specification in a standards track document.For an overview of our process, see proposal selection. Thank you again for contributing to Interop 2024!
Posted on behalf of the Interop team.
brandonmcconnell commentedon Feb 1, 2024
@bkardell What features from the official specification are not complete enough to move forward with this feature? The spec is complete and has been for years.
This feature has been suggested for the past few consecutive years via interop and otherwise.
More notably, this issue garnered more attention and praise and engagement than any other interop issue proposed, which I believe should be weighed heavily when considering proposed features for interop.
One of the primary functions of proposing issues for interop is to give the community the ability to vote on which issues they desire to see implemented in the web platform most. The results clearly show that this is a top priority if not THE top priority.
foolip commentedon Feb 1, 2024
@brandonmcconnell you're right that there's a lot of developer demand for this, that is very clear. The issue with the spec isn't really that it's "not yet complete enough to allow interoperable implementations", but that there are security issues that at least the Chrome team believes are serious enough to need solving before shipping. That is the topic of w3c/csswg-drafts#5092, and we now have a sketch of a solution that might work. I am going to follow up on that work so that the security issues can be resolved. (I did take a look while we were evaluating proposals too, but there just wasn't enough time to fix it there and then.)
brandonmcconnell commentedon May 18, 2024
@foolip (cc @tabatkins) Given the recent progress and resolutions in w3c/csswg-drafts#5092, and the exceeding demand on this interop proposal the past two consecutive years (#86 & #521), could we reconsider including it in this year's interop effort, as the blocker is now removed?
bkardell commentedon May 20, 2024
We can't, as part of Interop 2024. Interop choices and tests are carefully chosen so that we have measurable goals that don't significantly change during the year... But don't be too disheartened by that answer: It doesn't mean teams can't all prioritize it independently -- in my opinion, another benefit of the Interop project is just that it gets us collectively thinking/talking about priorities... So, it's totally possible if the situation regarding specs is resolved, that it might get interoperable support in the same year without actually being a part of the Interop project.
brandonmcconnell commentedon May 20, 2024
@bkardell Thanks, that's understandable 🙂