Typed attributes with attr()

Limited support Reference ↗

Use an HTML attribute as a typed CSS value, rather than only as text inside content. Here, data-width="320" becomes a width of 320 pixels.

<style>
  .card {
    width: 200px;
    max-width: 100%;
    padding: 1rem;
    box-sizing: border-box;
    background: lavender;
  }

  @supports (width: attr(data-width px, 200px)) {
    .card {
      width: attr(data-width px, 200px);
    }
  }
</style>

<div class="card" data-width="320">Sized from HTML</div>  

px tells CSS how to interpret the attribute. Keep the attribute unitless: write 320, not 320px. The fallback is used when the attribute is missing or cannot be parsed with that type.

The feature query keeps a 200-pixel width in browsers without the advanced syntax. Support for the older content: attr(...) form does not imply support for typed attributes in other properties.

Attribute values still need to be valid for the destination property. This does not make arbitrary HTML attributes usable as image URLs: URL values from attr() are restricted.