π What is the attr() Function?
The attr() CSS function allows you to use the value of an HTML attribute directly inside CSS. Today, attr() is mainly used in generated content (like with ::beforeand ::after), but Level 4 extends it for general property usage (still experimental).
Note
π― Why Use attr()?
- Display attribute values visually (e.g., data-* attributes)
- Create dynamic labels without JavaScript
- Build tooltips using pure CSS
- Auto-populate UI elements based on attributes
- Use dynamic values for content generation
π Syntax
attr() Syntax
attr(<attribute-name>, <type>?)Example types (Level 4 proposal):string, color, url, integer, length, etc. β οΈ Browser support varies β safest type is string.
π§ͺ Example 1 β Showing Data Attributes
Badge using attr()
.badge::after {
content: attr(data-count);
background: red;
color: white;
padding: 4px 8px;
border-radius: 10px;
}If HTML is:
HTML Example
<div class="badge" data-count="5"></div>β It renders a red badge showing **5**.
π§ͺ Example 2 β Tooltip With attr()
Tooltip Example
.tooltip:hover::after {
content: attr(data-tip);
position: absolute;
top: -40px;
left: 0;
padding: 8px;
background: #333;
color: white;
border-radius: 4px;
white-space: nowrap;
}HTML
<span class="tooltip" data-tip="Hello!">Hover me</span>Hovering shows the tooltip text taken from data-tip.
π§ͺ Example 3 β Labels Without JavaScript
Label with attr()
label::after {
content: " (" attr(data-required) ")";
color: #d00;
}HTML
<label data-required="required">Password</label>Renders β βPassword (required)β Perfect for form indicators.
π Example 4 β Dynamic Content for Cards
Card Title Example
.card::before {
content: attr(data-title);
font-weight: bold;
font-size: 1.2rem;
}HTML
<div class="card" data-title="Product Name"></div>π¨ Upcoming Feature β Using attr() for CSS Properties
CSS Level 4 adds support like:
Experimental Usage
.box {
width: attr(data-size length);
color: attr(data-color color);
}Note
π§ Practical Use Cases
- Badges with dynamic counts
- Tooltips without JavaScript
- ARIA labels or alt-text display
- Custom data-driven UI elements
- Auto-filling icons, prices, names from attributes
π± Example β Button Showing Keyboard Shortcut
Keyboard Shortcut Label
button::after {
content: " (" attr(data-shortcut) ")";
opacity: 0.6;
}HTML
<button data-shortcut="Ctrl+S">Save</button>β οΈ Common Mistakes
- β Trying to use attr() outside content in CSS β currently limited
- β Forgetting attribute must exist in HTML
- β Using complex types where browser support is incomplete
- β Expecting attr() to update instantly without re-render (depends on attribute changes)
Note
π₯ Summary
attr() is a powerful tool for using HTML attribute values inside CSS. It shines in generated content, enabling badges, tooltips, labels, and dynamic UI details without JavaScript. As CSS evolves, attr() will become even more flexible for property values.
Learn more βMDN Docs π