Published: Jan 15, 2025
The redesigned attr()
function
With CSS attr()
you can use the value of an HTML attribute in your CSS. Until now attr()
only worked within the content
property of pseudo-elements and could only parse values into a CSS <string>
.
The redesigned attr()
function, available from Chrome 133, unlocks more capabilities. You can now use attr()
with any CSS property—including custom properties—and it can parse values into data types other than <string>
.
Examples
In the following example the value of the color
property for div
uses the value from the data-color
attribute. This attribute value is parsed into a <color>
using attr()
and type()
. The fallback value is set to red
.
<div data-foo="blue">test</div>
div {
color: attr(data-foo type(<color>), red);
}
In the next example the view-transition-name
property is determined by the id
attribute of the element. The attribute gets parsed into a <custom-ident>
which is the required type for view-transition-name
. Without attr()
you had to declare a view-transition-name
for each card, whereas now you can do it it one go.
<div class="cards">
<div class="card" id="card-1"></div>
<div class="card" id="card-2"></div>
<div class="card" id="card-3"></div>
<div class="card" id="card-4"></div>
</div>
.card {
view-transition-name: attr(id type(<custom-ident>), none); /* card-1, card-2, card-3, etc. */
view-transition-class: card;
}
You can also parse values into a length by setting the type to any identifier that matches a CSS dimension unit or the %
character. In the following example the data-size
attribute gets parsed into a pixel value.
<div data-size="10">test</div>
div {
font-size: attr(data-size px);
}
When using attr()
without any type it parses the attribute to a CSS string, which is the same as the previous behavior.
Learn More
Find more information about attr()
in the specification and on MDN.