Choose a CSS value with if()
Use CSS if() to pick a badge background from a custom property, with fallbacks for other tones and older browsers.
Your badge gets its tone from a custom property. You want a warning tone to change its background and leave the same padding and text styles in place. If the property already carries that state, let the background declaration read it.
Choose a value from the tone
Put a style() condition inside CSS if(). The condition tests the computed value of a custom property on the element. CSS checks the branches in order and uses the value from the first true condition.
<!doctype html>
<title>Badge tones</title>
<style>
.badge {
padding: 2px 8px;
background-color: whitesmoke;
background-color: if(
style(--tone: warning): mistyrose;
else: whitesmoke
);
}
</style>
<span class="badge" style="--tone: warning">Retry needed</span>
<span class="badge">Ready</span>The warning badge uses mistyrose in a browser that supports the function. The other badge uses whitesmoke.
Inside the function, the colon separates a condition from the value it selects. The semicolon separates branches. The selected value still has to be valid for background-color.
Here the inline declaration stands in for any styling rule that sets --tone. Custom properties inherit by default. If a parent sets --tone: warning, a badge inside it can pick up that value. Set the default tone on the badge itself when you want each badge to own its state.
Keep the declaration and the else branch
The earlier background-color: whitesmoke gives a browser that rejects the new syntax a valid declaration. The else branch gives a browser that accepts the function a valid result for a badge without a matching tone.
Those cases matter because a value that becomes invalid after branch selection does not send CSS back to the earlier declaration. For example, omit else and leave the tone unset. The function yields the guaranteed-invalid value, so background-color uses its initial transparent value.
Use the function when a condition selects one property value. If the warning state also changes the icon, border and spacing, keep those declarations together in a selector that names the state. Check the computed background on a badge with no tone before removing the old rule.