![Bramus](https://web.dev/images/authors/bramus.jpg) Bramus [X](https://twitter.com/bramus) [GitHub](https://github.com/bramus) [Mastodon](https://front-end.social/@bramus) [Bluesky](https://bsky.app/profile/bram.us) [Homepage](https://www.bram.us/)

<br />


Published: Jan 15, 2025

<br />

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](https://drafts.csswg.org/css-values-5/#attr-notation), 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 in 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;
    }

<iframe height="600" style="width: 100%;" scrolling="no" title="Auto view-transition-name with attr() and type(<custom-ident>)" src="https://codepen.io/web-dot-dev/embed/yyBKLmd?default-tab=result" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> Go to the &amp;amp;lt;a href="https://codepen.io/web-dot-dev/pen/yyBKLmd"&amp;amp;gt;Pen&amp;amp;lt;/a&amp;amp;gt;. </iframe>

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](https://drafts.csswg.org/css-values-5/#attr-notation) and on [MDN](https://developer.mozilla.org/docs/Web/CSS/attr).