Dynamic Values: attr(), if(), Custom Functions and sibling-index()
The newest value functions: typed attr() that reads HTML attributes as lengths, colors or numbers in any property, if() with style(), media() and supports(), custom functions with @function, sibling-index() and sibling-count(), and fallbacks.
kvi5hnuCode Sprout team member8 min readOn this page
CSS has gained functions that make values depend on the document itself: an element's attributes, its position among its siblings, or a condition. Some are Baseline, and some are still Chromium and Safari only. This article explains each, with fallbacks you can use today.
attr(): reading HTML attributes
The classic attr() only worked in the content property and always produced a string (article 95):
abbr[title]::after { content: " (" attr(title) ")"; }
Typed attr() works in any property and parses the attribute as a given type:
.bar { width: attr(data-value type(<percentage>), 0%); }
.swatch { background: attr(data-color type(<color>), gray); }
.grid { grid-template-columns: repeat(attr(data-cols type(<integer>), 3), 1fr); }
.box { height: attr(data-h px, 100px); } /* a number in the attribute, with px added */
<div class="bar" data-value="72%"></div>
<div class="swatch" data-color="#2f7d4f"></div>
<div class="box" data-h="240"></div>
The forms:
| Form | Result |
|---|---|
attr(name) | the attribute as a string |
attr(name type(<length>)) | parsed with the syntax, as in @property (article 28) |
attr(name px) | a number in the attribute, with that unit added |
attr(name raw-string) | the raw text, without parsing (Chrome 136, Firefox 155, Safari 27.3 beta) |
attr(name, fallback) | the fallback when the attribute is missing or doesn't parse |
- Without a type, the value is a string.
width: attr(data-w)withdata-w="50px"doesn't work: the string"50px"isn't a length, so the declaration is invalid at computed-value time (article 27). - If the attribute doesn't parse as the type and there's no fallback, the declaration is also invalid at computed-value time.
- For security,
attr()can't produce URLs.url(attr(data-src))andtype(<url>)don't work, so attributes can't make the browser load resources.

The red bar is the untyped mistake: an earlier width: 50% doesn't save it, because the cascade had already picked the attr() declaration.
Typed attr() is in Chrome 133 and Firefox 155, and Safari has it in the 27.3 beta. Use it as an enhancement, with a fixed value in an earlier declaration:
.bar {
width: 50%;
width: attr(data-value type(<percentage>), 0%);
}
The plain earlier declaration is enough: browsers without typed attr() drop the second one at parse time. In supporting browsers, a missing or unparsable attribute uses attr()'s own fallback, so always give one. Use @supports (width: attr(x type(<length>), 0px)) only when several declarations must change together.
if(): conditional values
if() chooses between values inside a declaration. It tests conditions in order and uses the first that's true:
.button {
background: if(
style(--variant: danger): #b42318;
style(--variant: quiet): transparent;
else: var(--brand)
);
}
.layout { gap: if(media(width >= 48rem): 2rem; else: 1rem); }
.title { color: if(supports(color: oklch(0 0 0)): oklch(0.5 0.15 30); else: #8a3b12); }
| Condition | True when |
|---|---|
style(--x: value) | the element's custom property has that value (like container style queries, article 79, but on the element itself) |
media(...) | the media query matches |
supports(...) | the browser supports the declaration |
else | always: use it last, as a default |
Branches are separated by semicolons. If no branch matches and there's no else, the property is invalid at computed-value time. if() replaces many uses of the space toggle trick (article 27), and keeps a component's variants in one declaration.
if() is in Chrome 137 and the Safari 27.3 beta, not in Firefox yet. Don't use it for anything essential without a fallback declaration first: browsers that don't support it drop the declaration at parse time, so the earlier one is used.
Custom functions with @function
@function defines a reusable value function. Its name starts with two hyphens, like a custom property:
@function --negative(--value <length>) returns <length> {
result: calc(-1 * var(--value));
}
@function --shade(--color <color>, --amount <percentage>: 20%) returns <color> {
result: color-mix(in oklch, var(--color), black var(--amount));
}
.pull-left { margin-inline-start: --negative(1.5rem); }
.button:hover { background: --shade(var(--brand)); }
.button:active { background: --shade(var(--brand), 35%); }
-
Parameters are custom properties, with an optional type and an optional default after a colon.
-
returnsgives the result type, which is checked like a registered property's. -
The body can declare local variables and contain
@media,@supportsand@containerrules, which pick aresultconditionally:css@function --space(--step <number>) returns <length> { --base: 0.25rem; result: calc(var(--step) * var(--base)); @media (width >= 64rem) { result: calc(var(--step) * var(--base) * 1.25); } } -
Local variables don't leak out, but the body can read the calling element's custom properties, so
var(--brand)inside a function uses the value on the element where the function is called. -
Functions return a value, not declarations. Reusable groups of declarations, like Sass mixins, are a separate proposal (
@mixin) that no browser ships yet.
@function is in Chrome 139 and the Safari 27.3 beta, not yet in Firefox. Preprocessor functions remain the portable choice for now. Use CSS functions where the value depends on runtime data, such as custom properties set by JavaScript, or where browsers without them can get a simpler fixed value.
sibling-index() and sibling-count()
sibling-index() is an element's position among its siblings, starting at 1. sibling-count() is the total number of siblings, the element included. Both are integers usable in math functions:
ul { list-style: none; padding: 0; margin: 1rem; display: flex; gap: 0.5rem; font-family: system-ui, sans-serif; }
li {
width: 3.5rem; height: 3.5rem; border-radius: 8px; color: white; font-weight: 700;
display: grid; place-items: center;
background: oklch(0.55 0.14 calc(sibling-index() * (300 / sibling-count())));
animation: rise 0.6s calc((sibling-index() - 1) * 120ms) both;
}
@keyframes rise { from { opacity: 0; translate: 0 1rem; } }
Before these functions, staggering needed a custom property set on each element (style="--i: 3"), or one :nth-child() rule per position. Uses include animation delays, color ramps, z-index stacks of cards, and layouts that depend on the number of items, such as width: calc(100% / sibling-count()).

No item has a class or inline style: the same rule produces equal widths and an even color spread for any number of items.
They count element siblings only, ignoring text nodes, and every element in the parent, whatever its type. They're Baseline since August 2026, so use them freely, with no-animation or plain-color fallbacks if you need older browsers.
Browser support at a glance
| Feature | Chrome | Firefox | Safari | Status |
|---|---|---|---|---|
attr() in content, with fallback | yes | yes | yes | Baseline |
typed attr() in any property | 133 | 155 | 27.3 beta | not yet Baseline |
if() | 137 | no | 27.3 beta | not yet Baseline |
@function | 139 | no | 27.3 beta | not yet Baseline |
sibling-index(), sibling-count() | 138 | 154 | 26.2 | Baseline since August 2026 |
What's current
- Typed
attr()is part of Interop 2026, so it's likely to be Baseline soon once Safari 27.3 ships. if()and@functionwork in Chrome and the Safari beta. Firefox hasn't shipped them.@mixinand@apply, for reusing groups of declarations, are still only a draft.
Common questions
Why doesn't width: attr(data-width) work?
Without a type, attr() returns a string. Add a type: attr(data-width type(<length>), 0px), or a unit if the attribute holds a number: attr(data-width px, 0px).
Can I use attr() for background images?
No. For security, attr() can't create URLs. Set the image with an inline style or a custom property instead: style="--img: url(photo.jpg)" and background-image: var(--img).
What's the difference between if(style(...)) and a container style query?
if() tests the element's own custom properties and chooses one value. A style query (article 79) tests a container's properties and applies whole rules to its descendants.
Are CSS functions a replacement for Sass functions? Not yet everywhere, since Firefox hasn't shipped them. Unlike Sass functions, they run in the browser, so they can use custom properties that change with media queries, states or JavaScript.
Does sibling-index() count hidden elements?
Yes. It counts all element siblings in the DOM, whether they're displayed or not.
Summary
- Typed
attr()reads attributes as lengths, colors, numbers and other types in any property, with a fallback. Untypedattr()gives a string, andattr()can never produce URLs. if()picks a value withstyle(),media()andsupports()conditions, ending withelse.@functiondefines custom value functions with typed parameters, defaults, local variables and conditional results.sibling-index()andsibling-count()give an element's position and its number of siblings, for staggering and distributing. They're Baseline.- Typed
attr(),if()and@functionaren't Baseline yet, so put a plain declaration first or use@supports.
Practice questions
Each .rating element has data-stars="1" to "5". Write CSS that makes its width 1.2em per star, falling back to 6em without support.
Answer
.rating {
width: 6em;
width: calc(attr(data-stars type(<number>), 5) * 1.2em);
}
Write a padding that is 0.5rem when the element's --density is compact, 1.5rem when it's roomy, and 1rem otherwise, using if(). What should come before it for browsers without if()?
Answer
.card {
padding: 1rem;
padding: if(style(--density: compact): 0.5rem; style(--density: roomy): 1.5rem; else: 1rem);
}
The plain padding: 1rem comes first: browsers without if() drop the second declaration at parse time and keep the first.
Define a custom function --rem(--px) that converts a pixel number such as 24 into rem units, assuming a 16px root, and use it.
Answer
@function --rem(--px <number>) returns <length> {
result: calc(var(--px) / 16 * 1rem);
}
h2 { font-size: --rem(24); } /* 1.5rem */
Give eight cards in a row a fan effect, each rotated 4 degrees more than the last, centered around 0, without setting anything on individual cards.
Answer
.card { rotate: calc((sibling-index() - (sibling-count() + 1) / 2) * 4deg); }
With eight cards, the rotations run from -14deg to 14deg.
Review quiz
Test yourself on Part 4 with the CSS Part 4 review quiz.
Previous: Angles, Times, Resolutions, Ratios, Positions and Images
Next: Color Basics: Names, Hex, rgb(), hsl(), hwb(), currentColor and Transparency

More in CSS Course
Quiz: CSS Delicate Details
Twenty-five questions on the edge cases that surprise experienced developers: invalid custom properties, shorthands that reset values, layer order with !important, containing blocks, margin collapsing, specificity of :is() and :where(), intrinsic minimum sizes, and more, each checked in Chrome.
Quiz: CSS Interview Questions
Thirty front-end interview questions: cascade, specificity and layers, box model and margin collapsing, stacking contexts, positioning, flexbox and grid, responsive design, custom properties, performance, accessibility, modern selectors and architecture.
Quiz: CSS Course Final Exam
Thirty questions across the whole CSS course: syntax and error handling, selectors, the cascade and layers, values and units, color, the box model, backgrounds, positioning, flexbox, grid, responsive design, typography, generated content, effects, transforms, motion and architecture.
Quiz: CSS Architecture, Tooling and Debugging (CSS Part 17)
Twenty questions on modular CSS and BEM, layering a stylesheet, design tokens and theming, pattern libraries and safe refactoring, preprocessors and build tools, the at-rules reference, and debugging common CSS problems.
Discussion
Sign in to ask a question or share what you learned.