Web platform features explorer

attr()

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.

Status

Limited availability

MDN documentation

Browser support (view on caniuse.com)

Interop

Developer votes

Do you need this feature?
Let us know by leaving a 👍 reaction on the feedback issue. Don't forget to also leave a comment explaining your specific use case.

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]