Day 67 - Avoid Custom Properties in Shorthands
Emiliano Pisu
?? Sensei & Co-Host @ DevDojo IT ?? Speaker ?? Accessibility WCAG Expert ? Turning Designs into interactive things ??♂? Your friendly neighborhood Design Engineer
?? An Awesome CSS Link a Day – Day 67 ??
Why You Should Avoid Custom Properties in Shorthands
#AnAwesomeCSSLinkADay #YouDontMessWithCSS #CSS
Custom properties (--var) are a powerful feature in CSS, enabling dynamic styling and reusability. However, using them inside shorthand properties can lead to unexpected behavior and limit the flexibility of CSS defaults.
Introduction
Shorthand properties in CSS, like margin, padding, background, and border, reset all unspecified values to their defaults. When a custom property is used in a shorthand, any missing values become initial, potentially breaking styles. Understanding this issue helps maintain robust and predictable CSS.
?? The Issue: Invalid Custom Properties in Shorthands
Custom properties cannot hold complex shorthand values like "10px solid black". If they are used within a shorthand but evaluate to an invalid value, the entire declaration is ignored or resets unexpectedly.
Example of the Problem
:root { --main-border: solid; }
.box {
border: 2px var(--main-border) black; /* this breaks if --main-border is invalid */
}
If --main-border is not defined or incorrectly formatted, the entire border declaration fails. A safer approach is to set individual properties instead:
:root { --main-border: solid; }
.box {
border-width: 2px;
border-style: var(--main-border, solid);
border-color: black;
}
This way, each property remains functional even if the custom property is missing.
?? Today’s Link
For a deep dive into this topic, check out this great article by Manuel Matuzovi?:
?? Giveaways
? Why This Rocks
??? Join the Conversation
Let’s refine our CSS skills together! ??