Skip to main content
Dublin Library

The Publishing Project

Using the attr() css function

 

The attr allows developers to pull data from HTML attributes into CSS.

The idea is that, like data attributes and custom properties, you can use these bits of custom data to provide limited ways to customize the page's content.

Like data attributes these are stored in the HTML document itself.

Unlike custom properties defined with the @property at-rule, the value cannot be customized.

With this HTML

<blockquote cite="https://mozilla.org/en-US/about/">Mozilla makes
browsers, apps, code and tools
that put people before profit.</blockquote>
blockquote::after {
  display: block;
  content: ' (source: ' attr(cite) ') ';
  color: hotpink;
}

As it currently works, the functionality is very limited in that it only works with the content property.

While attr() is supported for effectively all browsers for the content property, CSS Values and Units Level 5 adds the ability to use attr() on any CSS property, and to use it for non-string values (like numbers, colors).

The syntax changes to something like this:

[data-background] {
  background-color: attr(data-background color, limegreen);
}

The new version of the attr() function takes three arguments:

The arguments of attr() are:

name
Gives the name of the attribute being referenced but without the possibility of a wildcard prefix.
If no namespace is specified (just an identifier is given, like attr(foo)), the null namespace is implied. (This is usually what’s desired, as namespaced attributes are rare. In particular, HTML and SVG do not contain namespaced attributes.) As with attribute selectors, the case-sensitivity of attr-name depends on the document language.
If attr() is used in a property applied to an element, it references the attribute of the given name on that element; if applied to a pseudo-element, the attribute is looked up on the pseudo-element’s originating element.
type
Specifies what kind of CSS value the attribute’s value will be interpreted into (the attr()’s substitution value) and what, if any, special parsing will be done to the value.
The allowed values are listed in attr() Types.
The default value is string if omitted.
value
Specifies a fallback value for the attr(), which will be substituted instead of the attribute’s value if the attribute is missing or fails to parse as the specified type.
If the type argument is string, defaults to the empty string if omitted; otherwise, defaults to the guaranteed-invalid value if omitted.

Because this version of attr() is not supported anywhere yet, we need to make sure we provide fallbacks using the original format for attr().

Edit on Github