midCSS

How does the CSS attr() function work?

Updated Apr 28, 2026

Short answer

The attr() function retrieves the value of an attribute of the selected element and uses it in the stylesheet.

Deep explanation

Currently, its primary use is inside the content property of pseudo-elements. It allows you to expose HTML data attributes visually in the UI without needing JavaScript to duplicate the text.

Real-world example

Creating a pure CSS tooltip system by reading the data-tooltip attribute and displaying it on hover.

Common mistakes

  • Trying to use `attr()` for CSS properties other than `content` (like width or color). While this is in the CSS spec, browser support is currently almost nonexistent.

Follow-up questions

  • What is the difference between attr() and CSS variables?

More CSS interview questions

View all →