Understanding the CSS attr() Function

CSS attr Function

Originally published on Makemychance.com

CSS is a powerful styling language, and among its lesser-known features is the attr() function. This function enables you to extract values from HTML attributes and incorporate them into your styles, making your web design more dynamic and responsive to the structure of your HTML. While it has limited use in modern CSS, it’s still a very handy feature — especially when paired with pseudo-elements.

In this article, we’ll explore how the attr() function works, where it can be used, current limitations, and future possibilities.


What is the CSS attr() Function?

The attr() function retrieves the value of an attribute from the selected HTML element and applies it to a CSS property.

Basic syntax:

content: attr(attribute-name);

Currently, it’s mostly used with the content property inside pseudo-elements like ::before or ::after.


Example: Display Custom Info with attr()

Let’s say you want to show additional information next to a paragraph, based on a custom attribute:

<p data-info="Important Notice">Read this</p>

<style>
p::after {
  content: " (" attr(data-info) ")";
  color: gray;
  font-style: italic;
}
</style>

Output:

Read this (Important Notice)

As you can see, the content of the data-info attribute is pulled and displayed after the paragraph text.


Common Use Cases

Here are some practical ways to use the attr() function:

  • Tooltips: Display information from title or data-* attributes.
  • Form Labels: Pull values from placeholder or aria-label.
  • Badges or Tags: Show dynamic labels or categories from custom data attributes.

Limitation of attr() in CSS

Despite its usefulness, the attr() function has some major limitations:

FeatureSupported?
Used with content✅ Yes
Used with color, width, font-size, etc.❌ No (not supported in most browsers)
Dynamic updates after attribute change❌ No (only reflects initial value in CSS)

If you’re trying to style an element’s width based on its data-width attribute, for example, attr() won’t work — yet.


The Future: attr() Beyond content

The CSS Working Group has proposed expanding attr() for other properties such as width, height, color, etc., like this:

div {
  width: attr(data-width px);
}

Unfortunately, this is not supported in major browsers as of now (2025), but CSS Houdini and future specs aim to improve this limitation.

If you’re curious, check out CSS Houdini for more on experimental styling capabilities.


Browser Support

BrowserSupports attr() in content
Chrome✅ Yes
Firefox✅ Yes
Safari✅ Yes
Edge✅ Yes
Opera✅ Yes

Final Thoughts

The attr() function is a powerful but currently limited tool in CSS. It’s perfect for enhancing content dynamically without JavaScript, especially in tooltips, labels, or badges. While it can’t yet be used for layout or visual properties, upcoming specifications may change that.

Source – MDN