Web features explorer

attr()

Limited availability

The attr() CSS function, in the context of any property, returns the value of an attribute of an HTML element, with the option to return it as a specific type or unit. You can set a default value for missing or invalid attributes.

Browser support (view on caniuse.com)

  • Chrome Not supported Bugs: 400981738
  • Chrome Android Not supported
  • Edge Not supported
  • Firefox Not supported Position: positive Bugs: 435426
  • Firefox for Android Not supported Position: positive
  • Safari Not supported Bugs: 26609
  • Safari on iOS Not supported Bugs: 26609

Need this feature?
Leave a 👍 on the feedback issue
Don't forget to also leave a comment explaining your specific use case.

MDN documentation

Interop

Developer use cases

  • Style images based on their focal point for better UX when images resize to fit different viewport widths. The CMS that calculates focal points outputs data- attributes, then site themes can decide if they want to write the needed styles in their stylesheets. CSS could look like this, defined once for all images site-wide: ```css [data-w-focus-x] { object-fit: cover; object-position: attr(data-w-focus-x) attr(data-w-focus-y); } ``` Style images based on their focal point for better UX when images resize to fit different viewport widths. The CMS that calculates focal points outputs data- attributes, then site themes can decide if they want to write the needed styles in their stylesheets. CSS could look like this, defined once for all images site-wide: ```css [data-w-focus-x] { object-fit: cover; object-position: attr(data-w-focus-x) attr(data-w-focus-y); } ``` [see original comment]
  • We're building a set of UI components that users can assemble into web pages. We want to dynamically assign an anchor name via prop, so that any element can be anchored to another. ```html <MyAnchorTarget data-anchor-name="--my-anchor-name" id="my-anchor-target-component" /> <MyToBeAnchored data-anchor-name="--my-anchor-name" id="my-to-be-anchored-component" /> <style> #my-anchor-target-component { anchor-name: attr(data-anchor-name) } #my-to-be-anchored-component { position-anchor: attr(data-anchor-name); } </style> ``` We're building a set of UI components that users can assemble into web pages. We want to dynamically assign an anchor name via prop, so that any element can be anchored to another. ```html <MyAnchorTarget data-anchor-name="--my-anchor-name" id="my-anchor-target-component" /> <MyToBeAnchored data-anchor-name="--my-anchor-name" id="my-to-be-anchored-component" /> <style> #my-anchor-target-component { anchor-name: attr(data-anchor-name) } #my-to-be-anchored-component { position-anchor: attr(data-anchor-name); } </style> ``` [see original comment]