attr() CSS Function
The attr() function reads the value of an HTML attribute and uses it in CSS, as text in content or, in newer browsers, as a typed value in any property.
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.
By default, attr() returns the attribute as a string. Newer versions of CSS add typed attr(), which can read an attribute as another type with type() or a unit, for example attr(data-size type(<length>)) or attr(data-width px), and can then be used with any property, such as width or color. A fallback value after a comma is used when the attribute is missing or invalid. Typed attr() is supported in Chrome and Edge (from version 133); support in Firefox and Safari is still arriving, so keep a fallback for other browsers.
Interactive Demo
- Apples
- Bananas
- Cherries
Syntax
attr() = attr( <attr-name> <attr-type>? , <declaration-value>? )
<attr-type> = type( <syntax> ) | raw-string | number | <attr-unit>
Values
- <attr-name>The name of the attribute to read from the element, for example data-label or title.
- <attr-type>Optional. How to interpret the attribute value. Without it, the value is a string. type(<syntax>) parses it as a CSS type such as type(<color>), type(<length>) or type(<number>); raw-string keeps it as a string; and a unit such as px, em, deg or % reads a number and adds that unit, for example attr(data-size px).
- <declaration-value>Optional. A fallback value, after a comma, used when the attribute is missing or cannot be parsed as the requested type.
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.
Desktop





Tablets & Mobile





