I have some CSS where I want a default color and then override it with a variable. When the CSS Variable doesn't exist, I want to use the fallback color.
:root {
/*--tintColor: red;*/
}
.text {
color: blue;
color: var(--tintColor);
}
When the variable isn't set like if its commented out the color becomes black. I want it in this case that the color falls back to the blue when the variable isn't defined. Is this possible?
CSS variables, more accurately known as CSS custom properties, are landing in Chrome 49. They can be useful for reducing repetition in CSS, and also for powerful runtime effects like theme switching and potentially extending/polyfilling future CSS features.
First of all: CSS variables can have a global or local scope. Global variables can be accessed/used through the entire document, while local variables can be used only inside the selector where it is declared. To create a variable with global scope, declare it inside the :root selector.
Moreover, these have either a global scope or a local scope and can be accessed using the var() function. You can avoid writing down repeated CSS values by using these variables, furthermore, these are easier to understand. It is also possible to override CSS variables with one another.
Custom properties (sometimes referred to as CSS variables or cascading variables) are entities defined by CSS authors that contain specific values to be reused throughout a document.
CSS variables are custom variables that you can create and reuse throughout your stylesheet. In this article, I will show you how to create CSS variables on the :root pseudo selector and show you how to access them using the var () function. It is best practice to define all of your variables at the top of your stylesheet.
The var () function is used to insert the value of a CSS variable. The syntax of the var () function is as follows: var ( name, value) Value. Description. name. Required. The variable name (must start with two dashes) value.
Custom properties (sometimes referred to as CSS variables or cascading variables) are entities defined by CSS authors that contain specific values to be reused throughout a document. They are set using custom property notation (e.g., --main-color: black;) and are accessed using the var() function (e.g., color: var(--main-color);).
The var() Function. Variables in CSS should be declared within a CSS selector that defines its scope. For a global scope you can use either the :root or the body selector. The variable name must begin with two dashes (--) and is case sensitive!
You can specify the fallback
property like var(--tintColor, blue)
- see demo below:
.text {
color: blue;
color: var(--tintColor, blue);
}
<div class="text">some text here</div>
<div class="text" style="--tintColor: red">some text here</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With