Skip to content
Tutorials Center
My learning

Topics

CSS Reference ยท Functions

The attr() function

Reference for the CSS attr() function: showing attribute text in content, the newer typed form for colors and lengths, fallbacks, and browser support caveats.

The attr() function reads the value of an HTML attribute from the element being styled. Its classic use is inside content to print an attribute as text in a ::before or ::after pseudo-element, such as showing a link's address after the link.

CSS
a[href]::after {
  content: " (" attr(href) ")";
}

A newer, typed form can use attribute values in properties other than content, for example a color or a length. That form is not available in every browser yet.

Try it

Attributes as generated text

Syntax

CSS
attr( <attr-name> )                       /* string, classic form */
attr( <attr-name> <type>? , <fallback>? ) /* typed form, newer */

content: attr(data-label);
width: attr(data-width px, 100px);  /* typed form */

Syntax and arguments

Part Description
attr-name The attribute to read. Case-sensitivity follows the document language (HTML attribute names are matched case-insensitively). A namespace can be given with `ns
<type> Newer form only. Tells the browser how to parse the text: string, color, url, number, length-percentage, a unit such as px or %, or raw-string. Check a compatibility table before relying on it.
fallback Value used if the attribute is missing or does not parse. In the classic form a missing attribute yields an empty string.

Usage notes

  • Classic use is safe everywhere: content: attr(...) is supported in all browsers and always produces text.
  • The result is text. It is not parsed as HTML, so you cannot inject markup this way, which is good for safety.
  • Generated content and accessibility: screen readers may or may not read ::before/::after text. Do not put essential information only in an attribute that you reveal through CSS; use real text or a proper accessible name.
  • Tooltips: attr(data-tip) styles are fine visually, but they do not work with keyboards or touch by themselves. Prefer the native title attribute sparingly, a popover, or a real disclosure widget.
  • Typed form: attr(data-size px) and attr(data-color color, black) avoid JavaScript for data-driven styling, but until your target browsers support it, use custom properties via inline style="--x: 10px" and var() instead.
  • Printing: attr(href) after links is a classic print-stylesheet trick; apply it inside @media print.

Browser support

Using attr() inside content works in every browser. The typed form that works in any property is newer and has uneven support; check a compatibility table before using it.