Cody
Cody

Reputation: 149

How to prevent CSS from overwriting a previous value when using variables

So, I'm trying to design a style sheet that will provide us with quick and easy customization options (some of the team members have limited understanding off CSS and it would be safer to construct a 'theme sheet' that can be easily editted)

I'm declaring my variables in :root and using them later in the css file, but I've observed that if the css can't find the variable, it reverts to default values instead of using a value provided earlier in the CSS.

:root {
    --global-font: empty;
    --global-font-color:empty;
    --global-bg-color: #282a33;
}

I'm currently setting it to inherit as an attempt to combat this issue but that still pulls the value from its parent container and the webpage has default themes already selected that if we inherit, it often breaks them.

body
{
    font: var(--global-font,inherit);
    color: var(--global-font-color,inherit);
    background-color:var(--global-bg-color,inherit);
}

My eventual solution was to comment out all the variables except those being used. That allowed me to specify a default value in the second field for var() that it will always default to unless the variable did exist. It isn't quite what I was aiming for but I believe its the only solution within the scope of basic css.

Upvotes: 1

Views: 1690

Answers (1)

BoltClock
BoltClock

Reputation: 723568

Sorry, due to the nature of cascading variables, it is not possible to specify a var() expression that will invalidate just the declaration it's in without affecting the rest of the cascade. From the spec:

Note: The invalid at computed-value time concept exists because variables can’t "fail early" like other syntax errors can, so by the time the user agent realizes a property value is invalid, it’s already thrown away the other cascaded values.

Your custom properties will have to be made mandatory and you will have to ensure that your theme authors specify all of them.

Upvotes: 2

Related Questions