Skip to content

attr() support extended capabilities (Interop 2023) #86

Closed

Description

@brandonmcconnell

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

Tests

wpt / css / q: css-values

More tests courtesy of @karlcow (from comment below) using…

find css -type f | xargs grep 'attr(' | sort | grep -v 'ref.html' | grep -v '.py' | sed 's,\:.*,,' | sed 's,^,https://wpt.fyi/,' | uniq

wpt.fyi/css/css-align/self-alignment/self-align-safe-unsafe-flex-001.html
wpt.fyi/css/css-align/self-alignment/self-align-safe-unsafe-flex-002.html
wpt.fyi/css/css-align/self-alignment/self-align-safe-unsafe-flex-003.html
wpt.fyi/css/css-align/self-alignment/self-align-safe-unsafe-grid-001.html
wpt.fyi/css/css-align/self-alignment/self-align-safe-unsafe-grid-002.html
wpt.fyi/css/css-align/self-alignment/self-align-safe-unsafe-grid-003.html
wpt.fyi/css/css-conditional/at-supports-namespace-001.html
wpt.fyi/css/css-content/attr-case-sensitivity-001.html
wpt.fyi/css/css-content/attr-case-sensitivity-002.html
wpt.fyi/css/css-content/attr-case-sensitivity-003.html
wpt.fyi/css/css-gcpm/string-set-012.html
wpt.fyi/css/css-values/attr-color-invalid-cast.html
wpt.fyi/css/css-values/attr-color-invalid-fallback.html
wpt.fyi/css/css-values/attr-color-valid.html
wpt.fyi/css/css-values/attr-in-max.html
wpt.fyi/css/css-values/attr-invalid-type-001.html
wpt.fyi/css/css-values/attr-invalid-type-002.html
wpt.fyi/css/css-values/attr-invalid-type-008.html
wpt.fyi/css/css-values/attr-length-invalid-cast.html
wpt.fyi/css/css-values/attr-length-invalid-fallback.html
wpt.fyi/css/css-values/attr-length-valid-zero-nofallback.html
wpt.fyi/css/css-values/attr-length-valid-zero.html
wpt.fyi/css/css-values/attr-length-valid.html
wpt.fyi/css/css-values/attr-px-invalid-cast.html
wpt.fyi/css/css-values/attr-px-invalid-fallback.html
wpt.fyi/css/css-values/attr-px-valid.html
wpt.fyi/css/css-values/calc-rgb-percent-001.html
wpt.fyi/css/css-variables/variable-generated-content-dynamic-001.html
wpt.fyi/css/cssom/css-style-attr-decl-block.html
wpt.fyi/css/cssom/serialize-values.html

Rationale

This has been a highly anticipated feature for several years and would do a great deal to equip developers to utilize values defined in markup within their styles. The workaround thus far has been to exclude these values within CSS custom properties (variables), but that often requires having values in two places— (1) an attribute for proper syntax for a given element and (2) a CSS custom property for usage within stylesheets. but for many, especially non-devs who simply work with HTML, this

Supporting rationale

  • Many great arguments voiced in this Chromium Dev thread (246571)
  • attr() is more semantic — avoiding forcing styles into the markup using CSS custom properties as a workaround
  • avoiding redundancy — using CSS custom properties instead of being able to use attr() properly often requires addtl setup within markup simply to allow value exposure to CSS
  • would make data management more achievable in copywriting stage where editors work more predominantly with markup than they do inline styling

Supporting examples

Click to expand relevant example

A11Y labels (tooltip example)

❌ w/o extended `attr()` features — using `data-` attr workaround
```html
<button
aria-label="Some label here"
data-label="Some label here"
>
Button
</button>

<style>
button:hover::after,
button:focus::after {
    /* FALLBACK VALUE NOT SUPPORTED */
    content: attr(data-label);
}
</style>
```

❌ w/o extended `attr()` features — using CSS custom properties workaround
```html
<button
aria-label="Some label here"
style="--label: 'Some label here'"
>
Button
</button>

<style>
button:hover::after,
button:focus::after {
    content: var(--label, "default label");
}
</style>
```

✅ w/ extended `attr()` features

```html
<button aria-label="Some label here">Button</button>

<style>
button:hover::after,
button:focus::after {
    content: attr(aria-label, "default label");
}
</style>
```

<type-or-unit> (units example)

❌ w/o extended `attr()` features — using `data-` attr workaround
```html
<div data-size="100" style="width: 100px; height: 100px;"></div>

<style>
div {
    background-color: cyan;
    /* VALUE TYPE-CASTING NOT SUPPORTED */
}
div::after {
    content: "Size: " attr(data-size);
}
</style>
```

❌ w/o extended `attr()` features — using CSS custom properties workaround
```html
<div style="--size: 100px; --size-label: '100';"></div>

<style>
:root {
    /* Coupling variables creates risk of mismatched values */
    --fallback-size: 50px;
    --fallback-size-label: "50";
}
div {
    background-color: cyan;
    /* VALUE TYPE-CASTING NOT SUPPORTED */
    width: var(--size, var(--fallback-size));
    height: var(--size, var(--fallback-size));
}
div::after {
    content: "Size: " var(--size-label, var(--fallback-size-label));
}
</style>
```

✅ w/ extended `attr()` features

```html
<div data-size="100"></div>

<style>
:root {
    --fallback-size: "50";
}
div {
    background-color: cyan;
    width: attr(data-size px, var(--fallback-size));
    height: attr(data-size px, var(--fallback-size));
}
div::after {
    content: "Size: " attr(data-size, var(--fallback-size));
}
</style>
```

background-image (url example)

❌ w/o extended attr() features — using data- attr workaround (not possible without CSS custom properties)

<div
  data-image="/images/background.jpg"
  style="--image: url('/images/background.jpg');"
></div>

<style>
  div {
    background-image: var(--image);
  }
  div::after {
    content: "Image filepath: " attr(data-image);
  }
</style>

❌ w/o extended attr() features — using CSS custom properties workaround

<div
  style="
    --image-filepath: '/images/background.jpg';
    --image: url('/images/background.jpg');
  "
></div>

<!-- ** important to note here that interpolating the value of `--image-filepath` into `--image` is not yet supported in CSS custom properties, so `--image: url(var(--image-filepath))` would not work -->

<style>
  div {
    background-image: var(--image, none);
  }
  div::after {
    content: "Image filepath: " var(--image-filepath, 'no file present');
  }
</style>

✅ w/ extended attr() features

<div data-image="/images/background.jpg"></div>

<style>
  div {
    background-image: attr(data-image url, '');
  }
  div::after {
    content: "Image filepath: " attr(data-image, 'no file present');
  }
</style>

Current Browser Compatibility (view on MDN)

Expand to see screenshot of CSS attr() browser compatibility chart (from MDN)

CSS attr() function Current Browser Compatibility

Activity

  1. foolip commented on Jun 2, 2022

    @foolip
    Member

    Hi @brandonmcconnell! We haven't started planning for Interop 2023 yet, but I've created #78 which you can watch to see when things start happening. At some point there will be a public proposal process, and I'd suggest raising this then.

    Interpreting the compat tables is a bit tricky since it's just a lot of red, can you give a few code examples of things that already work in browsers and what things do not?

  2. brandonmcconnell commented on Jun 15, 2022

    @brandonmcconnell
    Author

    Sure, I'll post a few examples later today/tomorrow. Thanks!

  3. una commented on Sep 14, 2022

    @una

    Extended attr() support would be really useful!

  4. foolip commented on Sep 16, 2022

    @foolip
    Member

    @brandonmcconnell We just opened up for Interop 2023 proposals yesterday, see https://github.com/web-platform-tests/interop/blob/main/2023/README.md for the process and what to expect.

    You have used the same sections as our Focus Area proposal template, so if you like I can change the label to make it such a proposal. Alternatively you could recreate it using https://github.com/web-platform-tests/interop/issues/new?assignees=&labels=focus-area-proposal&template=focus-area-proposal.yml. Which would you prefer?

  5. brandonmcconnell commented on Sep 16, 2022

    @brandonmcconnell
    Author

    @foolip If you wouldn't mind just re-labeling it—if that would suffice—that works for me. Thanks!

  6. added
    focus-area-proposal
    and removed on Sep 16, 2022
  7. added this to the milestone on Sep 16, 2022
  8. foolip commented on Sep 23, 2022

    @foolip
    Member

    @brandonmcconnell for the tests you linked to this wpt.fyi query:
    https://wpt.fyi/results/css?label=master&label=experimental&aligned&q=attr&view=subtest

    That includes a lot of tests that aren't about attr(), but this subset is probably mostly about attr():
    https://wpt.fyi/results/css/css-values?label=master&label=experimental&aligned&view=subtest&q=attr

    At a glance I think some tests are missing, like for percentages and URLs.

    If anyone who knows this feature well could take a look, that'd be very helpful!

  9. gsnedders commented on Sep 24, 2022

    @gsnedders
    Member

    At a glance I think some tests are missing, like for percentages and URLs.

    It's somewhat unsurprising that we have few tests given lack of implementations; certainly there could be a vastly larger test suite for this.

  10. brandonmcconnell commented on Sep 24, 2022

    @brandonmcconnell
    Author

    @brandonmcconnell for the tests you linked to this wpt.fyi query: https://wpt.fyi/results/css?label=master&label=experimental&aligned&q=attr&view=subtest

    That includes a lot of tests that aren't about attr(), but this subset is probably mostly about attr(): https://wpt.fyi/results/css/css-values?label=master&label=experimental&aligned&view=subtest&q=attr

    @foolip You're absolutely right. Not sure how that happened, but I've replaced it above now. Thanks!

  11. karlcow commented on Sep 26, 2022

    @karlcow

    Maybe
    find css -type f | xargs grep 'attr(' | sort | grep -v 'ref.html' | grep -v '.py' | sed 's,\:.*,,' | sed 's,^,https://wpt.fyi/,' | uniq

    https://wpt.fyi/css/css-align/self-alignment/self-align-safe-unsafe-flex-001.html
    https://wpt.fyi/css/css-align/self-alignment/self-align-safe-unsafe-flex-002.html
    https://wpt.fyi/css/css-align/self-alignment/self-align-safe-unsafe-flex-003.html
    https://wpt.fyi/css/css-align/self-alignment/self-align-safe-unsafe-grid-001.html
    https://wpt.fyi/css/css-align/self-alignment/self-align-safe-unsafe-grid-002.html
    https://wpt.fyi/css/css-align/self-alignment/self-align-safe-unsafe-grid-003.html
    https://wpt.fyi/css/css-conditional/at-supports-namespace-001.html
    https://wpt.fyi/css/css-content/attr-case-sensitivity-001.html
    https://wpt.fyi/css/css-content/attr-case-sensitivity-002.html
    https://wpt.fyi/css/css-content/attr-case-sensitivity-003.html
    https://wpt.fyi/css/css-gcpm/string-set-012.html
    https://wpt.fyi/css/css-values/attr-color-invalid-cast.html
    https://wpt.fyi/css/css-values/attr-color-invalid-fallback.html
    https://wpt.fyi/css/css-values/attr-color-valid.html
    https://wpt.fyi/css/css-values/attr-in-max.html
    https://wpt.fyi/css/css-values/attr-invalid-type-001.html
    https://wpt.fyi/css/css-values/attr-invalid-type-002.html
    https://wpt.fyi/css/css-values/attr-invalid-type-008.html
    https://wpt.fyi/css/css-values/attr-length-invalid-cast.html
    https://wpt.fyi/css/css-values/attr-length-invalid-fallback.html
    https://wpt.fyi/css/css-values/attr-length-valid-zero-nofallback.html
    https://wpt.fyi/css/css-values/attr-length-valid-zero.html
    https://wpt.fyi/css/css-values/attr-length-valid.html
    https://wpt.fyi/css/css-values/attr-px-invalid-cast.html
    https://wpt.fyi/css/css-values/attr-px-invalid-fallback.html
    https://wpt.fyi/css/css-values/attr-px-valid.html
    https://wpt.fyi/css/css-values/calc-rgb-percent-001.html
    https://wpt.fyi/css/css-variables/variable-generated-content-dynamic-001.html
    https://wpt.fyi/css/cssom/css-style-attr-decl-block.html
    https://wpt.fyi/css/cssom/serialize-values.html

  12. changed the title [-]Add support for CSS `attr()` function extended capabilities[/-] [+]`attr()` support extended capabilities[/+] on Oct 2, 2022
  13. 18 remaining items

  14. brandonmcconnell commented on Nov 15, 2022

    @brandonmcconnell
    Author

    Related to this conversation, from another conversation happening on the value() idea proposal:

    @brandonmcconnell:

    Perhaps for this case specifically, what could help here to avoid any additional security vulnerabilities with value() would be some secure way for only first-party scripts to whitelist elements that would allow access to them using value() in this way, something like a "public" attribute, but more secure than a mere attribute.

    @arturjanc:

    Limiting value() to data explicitly marked as readable by stylesheets seems like a reasonable possible solution to explore here.

    @brandonmcconnell:

    Yeah, I'm all for that!

    With that in mind, maybe this could actually work using something as simple as a special HTML attribute that browsers will require elements to have in order to execute either attr() or value() on them since only first-party scripts would have the ability to add such an attribute post-pageload which are already trusted anyway.

    CSS attr() and value() would then be limited to only those "whitelisted" elements. 👏🏼

  15. jakearchibald commented on Nov 16, 2022

    @jakearchibald
    Contributor

    @arturjanc

    Sure, take a look at the first two restrictive examples of the use of DOMPurify and the native Sanitizer API from https://github.com/cure53/DOMPurify and https://web.dev/sanitizer/ respectively:

    Hmm, good example. Could attr() restrictions be limited to places that cannot already select based on attribute? So, attr() would fail on inline styles, but work in stylesheets?

  16. arturjanc commented on Nov 16, 2022

    @arturjanc

    This would address part of the problem, but sadly not everything we should arguably care about. The two major remaining cases I can think of are:

    • Pages with a strict CSP + style-src 'self' 'unsafe-inline'. In the event of an HTML injection bug they are currently generally safe from selector-based exfiltration of attribute values (because the attacker can't @import new stylesheets to recursively leak subsequent characters), but we'd allow the attacker to inject a <style> that can directly leak the contents of all attributes.
    • CSS sanitizers which allow <style> elements and parse/sanitize the stylesheet to remove "dangerous" features (e.g. at-rules, etc.) but allow the use of CSS functions. This one is somewhat hypothetical though, I don't have a concrete example of such a sanitizer.

    At a high level, my guess is that the two directions in which we can go to mitigate these concerns would be:

    1. Prevent the use of attribute values within url(), in particular ban concatenation with the string attribute type inside url().
    2. Allow the use of attr() for explicitly allowlisted elements/attributes, e.g. we could have a data-css- attribute prefix and make any such values accessible to CSS, or have a per-element attribute that would allow the given element's attributes to be used with attr() as mentioned by @brandonmcconnell above.

    These approaches are not mutually exclusive, e.g. the attribute allowlisting approach could be something that premits the use of attr() within url(), as long as the attribute/element is allowlisted for access from CSS. I'm kind of hopeful that something along these lines will be a reasonable path forward here.

  17. jakearchibald commented on Nov 16, 2022

    @jakearchibald
    Contributor

    The restrictions in url() seem ok, but whatever restrictions are applied, it'd be nice to have a way to opt-out of the restrictions.

  18. arturjanc commented on Nov 16, 2022

    @arturjanc

    In the model I was thinking of above, opting out of the restrictions would happen per-element; if you have an element on which you want to use attr() within a url(), you'd add an attribute to expose the value to CSS, e.g.

    <style>
    *[data-animal] {
      background-image: url(concat('https://site.example/generate-animal?animal=', attr(data-animal string)));
    }
    </style>
    

    and

    <div data-animal="hippopotamus" allow-attribute-access-from-css></div>
    

    or

    <div data-animal="meerkat" allow-attribute-access-from-css="data-animal"></div>
    

    (the attribute name is obviously bad, this is just for the sake of discussion)

  19. brandonmcconnell commented on Nov 16, 2022

    @brandonmcconnell
    Author

    I really like that idea, @arturjanc. It does really well to marry the two ideas of enforcing default restrictions while allowing exposure to CSS via whitelisting as we previously discussed.

    We can certainly bikeshed on the name some more, as you mentioned. Maybe something like cssx (CSS eXpose), where space-delimited attribute names can be used optionally.

    No special access to any attributes:

    <div data-username="sampleuser" data-password="abc123"></div>
    .password-stasher {
      background-image: url(concat('/?usr=', attr(data-username string), '&pwd=', attr(data-password string)));
      /* Should this property be computed at all?
         When attributes are used which are not exposed,
         should the attributes be replaced with empty strings
         (nullish for type), or break the property value completely */
    }

    Allow access to all attributes:

    <div data-username="sampleuser" data-password="abc123" cssx></div>
    .password-stasher {
      background-image: url(concat('/?usr=', attr(data-username string), '&pwd=', attr(data-password string)));
      /* evaluates to `url('/?usr=sampleuser&pwd=abc123')` */
    }

    Allow access to specific attributes:

    <div data-username="sampleuser" data-password="abc123" cssx="data-username"></div>
    .password-stasher {
      background-image: url(concat('/?usr=', attr(data-username string), '&pwd=', attr(data-password string)));
      /* Per the same question(s) I posed in the first example,
         would this property value break completely or evaluate to
         `url('/?usr=sampleuser&pwd=')` where `attr(data-password string)`
         evals to an empty string (nullish for type) */
    }

    If we want to be a bit more verbose/explicit with the naming, we could use names like these (below) which directly relate to their CSS function couterparts

    • css-expose-attr
    • css-expose-value (for value())
  20. jgraham commented on Nov 16, 2022

    @jgraham
    Contributor

    Just a note: this design discussion should probably happen in either the HTML repo, or the relevant CSS repo; the Interop repo is likely missing many of the people who would like to be involved.

  21. ExE-Boss commented on Dec 10, 2022

    @ExE-Boss

    Note that it’s not possible to use any CSS function inside url(…) since it’s a legacy thing which always parses its first argument as a raw string: https://drafts.csswg.org/css-syntax/#consume-a-url-token

  22. brandonmcconnell commented on Dec 10, 2022

    @brandonmcconnell
    Author

    @ExE-Boss Could url() be adjusted to accept any URL token type in CSS? Once CSS functions become available, it will be possible to concatenate and convert string types to URL types AFAIK.

  23. tabatkins commented on Dec 10, 2022

    @tabatkins

    Yes, we created the src() function precisely to allow that use-case (using a function in url()).

  24. nairnandu commented on Feb 1, 2023

    @nairnandu
    Contributor

    Thank you for proposing attr() for inclusion in Interop 2023.

    We wanted to let you know that this proposal was not selected to be part of Interop this year. We had many strong proposals, and could not accept them all. There is a lot of support for attr(), but it may need more standards work before it’s ready for adoption. Resubmitting a proposal for this feature in the future would be welcome.

    For an overview of our process, see the proposal selection summary. Thank you again for contributing to Interop 2023!

    Posted on behalf of the Interop team.

  25. brandonmcconnell commented on Sep 22, 2023

    @brandonmcconnell
    Author

    @foolip @nairnandu Could we look into resurrecting this one for Interop 2024 as well?

  26. changed the title [-]`attr()` support extended capabilities[/-] [+]`attr()` support extended capabilities (Interop 2023)[/+] on Oct 3, 2023
  27. brandonmcconnell commented on Oct 3, 2023

    @brandonmcconnell
    Author

    Created a new issue for this in Interop 2024: #521

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    focus-area-proposal

    Type

    No type

    Projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions