Maybe don't use custom properties in shorthand properties
posted on
I've already written about how the fact that the initial value of a custom property is a guaranteed-invalid value can lead to unexpected results. Today, I realized how that can be problematic when you use custom properties in shorthand properties.
A quick recap
When you set a valid value for a property followed by another declaration with an invalid value, the second declaration will be ignored.
div {
background-color: #F00;
background-color: fcktrmp;
}
/* Result: #F00 background */
That's one of the reasons why CSS is so great. It's forgiving.
When the value in the second declaration is a custom property that doesn't exist, the declaration is not ignored. Either the property’s inherited value or its initial value, depending on whether the property is inherited or not, will be used instead.
div {
background-color: #F00;
background-color: var(--not-set);
}
/* Result: transparent background */
You can learn more about that in Day 1: custom properties and fallbacks and Invalid at computed-value time.
Invalid custom properties in short hand properties
Okay, now that we know that undeclared custom properties are invalid, let's see what happens when we use them in shorthand properties.
div {
border-style: solid;
border-width: 20px var(--border--inline) 10px;
}
The --border-inline
custom property doesn't exist, which means it's invalid. That's enough to invalidate the entire declaration.
We get a different result if we don't use the shorthand property because the missing custom property only invalidates one property.
div {
border-style: solid;
border-block-start-width: 20px;
border-inline-width: var(--border--inline);
border-block-end-width: 10px;
}
For the sake of completeness, here's how it looks like when the property exists.
div {
--border-inline: 30px;
border-style: solid;
border-block-start-width: 20px;
border-inline-width: var(--border-inline);
border-block-end-width: 10px;
}
Of course, you're also save if you provide a fallback for your custom property.
div {
border-style: solid;
border-block-start-width: 20px;
border-inline-width: var(--border-inline, 30px);
border-block-end-width: 10px;
}
That an invalid custom property invalidates the entire declaration isn't surprising, but I didn't consider it until I saw one of my declarations break. I guess it's just good to know that, especially if you're working a lot with custom properties. So, maybe don't use custom properties in shorthand properties or use custom properties but don't use shorthand properties.