Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

attr() — typed attribute value

`attr()` substitutes an attribute value from the same element into a CSS property, optionally parsing it as a requested type.

Version: CSS modules; structured CSSWG indexes reconciled with pinned MDN BCD; Chromium 152 scope gate, per-example verification still required

Syntax

attr( <attr-name> <attr-type>? , <declaration-value>? )

attr() substitutes an attribute value from the same element into a CSS property, optionally parsing it as a requested type.

The example uses attr(data-size type(<length>), 17px): valid 42px passes through, an invalid or missing value produces 17px, and boundary 0px remains a valid zero instead of invoking the fallback.

Grammar: attr( <attr-name> <attr-type>? , <declaration-value>? ).

type() requests syntax parsing and the result is checked at computed-value time; raw-string preserves literal text. A typed lookup without an effective fallback can invalidate the declaration at computed-value time. <url> is forbidden for security, and use on a pseudo-element reads the originating element.

Examples

const make=value=>{const el=document.createElement('div');document.body.append(el);el.style.cssText='display:block;width:attr(data-size type(<length>), 17px);height:1px';if(value!==undefined)el.setAttribute('data-size',value);return getComputedStyle(el).width};const valid=make('42px'),invalid=make('wide'),missing=make(undefined),zero=make('0px');if(valid!=='42px'||invalid!=='17px'||missing!=='17px'||zero!=='0px')throw new Error('typed attr() boundary mismatch');console.log('valid='+valid+'; invalid='+invalid+'; missing='+missing+'; zero='+zero);

Result

valid=42px; invalid=17px; missing=17px; zero=0px

`attr()` substitutes an attribute value from the same element into a CSS property, optionally parsing it as a requested type.

Sources