CSS Reference Function


attr() (abbreviation for ‘attribute’) is a function that returns as a string the value of an attribute of an element.

For example, attr(X) returns the value of attribute X specified on the element. If the element does not have an attribute X, an empty string is returned. For example, links <a> have an href attribute which determines the location to which the link points. Using the content property with the attr() function you can retrieve the value of the URL in the href attribute, which is pretty powerful. This can be used in print style sheets to print the URL to which a link points, right after the content of that link (using the ::after pseudo-element). For example:

@media print {
  a[href]::after {
    content: attr(href);

The above rule selects all links that have an href attribute (using the attribute selector), retrieves the value of the href attribute using the attr() function, and then uses that value as the content of the ::after pseudo-element, which will be inserted into the links after the link’s content.

The attr() function can retrieve the value of any attribute of an element, including custom HTML5 data-* attributes. For example:

<li data-label="todo">Buy Milk</li>
li::before {
  content: attr(data-label);
  color: grey;

In CSS3, the attr() expression gets a new syntax. The new syntax is not stable, not supported in any browser yet, and there are no examples of use cases anywhere. The specification also says that the new syntax is at risk and may be dropped during the Candidate Recommendation stage. If the new syntax is not dropped, this entry will be updated with the new values. The syntax looks like the following:

attr( <attr-name> <type-or-unit>? [ , <attr-fallback> ]? )

where <attr-name> is the attribute name, <type-or-unit> is an optional argument which tells the user agent how to interpret the attribute value, and defines a type for the attr() expression. If omitted, ‘string’ is implied. The <attr-fallback> argument represents a fallback value, which is used if the named attribute is missing, or its value cannot be parsed into the given type or is invalid/out-of-range for the property. If it’s absent, the default value for the given <type-or-unit< (from the list below) is implied.

The type or unit argument can be one of the following: ‘string’, ‘color’, ‘url’, ‘integer’, ‘number’, ‘length’, ‘angle’, ‘time’, or ‘frequency’.

As mentioned above, this entry will be updated with an elaborated description and examples if the new expression syntax is not dropped in the future.

Browser Support

Basic attr() usage is supported in all major browsers: Chrome, Firefox, Safari, Opera, Internet Explorer, and on Android and iOS.

Written by

Last updated December 11, 2016 at 9:47 pm by Mary Lou

Do you have a suggestion, question or want to contribute? Submit an issue.