attr() CSS Function
Description
The attr() CSS function allows you to retrieve the value of an attribute from an HTML element and use it in your styles. It is particularly useful for dynamically displaying content based on the attributes of elements, such as tooltips, labels, or counters, without requiring JavaScript. While attr() is most commonly used with the content property in pseudo-elements like ::before and ::after, its support in other CSS properties is currently limited in many browsers, though evolving in modern CSS specifications.
For example, if you have an a element with a title attribute, you can use attr() to display the title in a tooltip-like fashion using CSS only:
a::after {
content: " (" attr(title) ")";
color: gray;
font-size: 0.9em;
}
This will automatically append the value of the title attribute to the link text.
Another practical usage is with img elements to display alternate text:
img::after {
content: attr(alt);
display: block;
text-align: center;
color: #555;
}
Here, attr(alt) pulls the alt attribute from the img and renders it below the image.
It’s important to note that attr() retrieves the attribute as a string, and although the CSS Values and Units Module Level 4 introduces typed values for width, numbers, or lengths, browser support is still limited.
Syntax
attr( <attr-name> <type-or-unit>? [ , <attr-fallback> ]? )
Values
- <attr-name>Is the name of an attribute on the HTML element referenced in the CSS.
- <type-or-unit>Is a keyword representing either the type of the attribute's value, or its unit, as in HTML some attributes have implicit units. The following keywords are valid: <string>, <color>, <url>, <integer>, <number>, <angle>, <time>, <deg>, and also CSS units like em, ex, px, rem, vw, vh, vmin, vmax, mm, cm, in, pt, or pc
- <attr-fallback>The value that will be used if the attribute is absent or the browser cannot receive it.
Example
Browser Support
The following information will show you the current browser support for the CSS attr() function. Hover over a browser icon to see the version that first introduced support for this CSS function.
This function is supported by all modern browsers.
Desktop
Tablets & Mobile
Last updated by CSSPortal on: 31st December 2025
