CSS - Variables
Syntax and Declaration
CSS variables, also known as CSS custom properties, are declared using a special syntax. To declare a CSS variable, you start with two dashes (--
) followed by the variable name. The variable name can consist of letters, numbers, underscores, and hyphens, but it must start with two dashes.
Example: Declaring a CSS Variable
:root {
--primary-color: #007bff;
--font-size: 16px;
}
In this example, we declare two CSS variables: --primary-color
and --font-size
. The values assigned to these variables are #007bff
(a hexadecimal color code) and 16px
(a font size), respectively.
When naming CSS variables, it's a good practice to use descriptive and meaningful names that reflect the purpose or value they represent. This helps keep your code readable and maintainable. It's also common to use kebab-case (lowercase letters separated by hyphens) for variable names to maintain consistency with CSS property naming conventions.
CSS variables have a specific scope determined by where they are declared. There are two main scopes for CSS variables:
Scope | Description |
---|---|
Global scope | CSS variables declared within the :root pseudo-class have a global scope. This means they can be accessed and used by any element in the document. The :root pseudo-class represents the root element of the document tree, which is typically the <html> element. |
Local scope | CSS variables can also be declared within a specific selector, such as a class or an element. In this case, the variable has a local scope and can only be used within that particular selector or its descendants. Local variables will override global variables with the same name. |
Example: Local Scope of CSS Variables
.button {
--button-color: #ff0000;
background-color: var(--button-color);
}
In this case, the --button-color
variable is declared within the .button
class selector. It can only be used within the .button
class or its descendants.
By default, CSS variables are inherited by descendant elements. This means that if a variable is declared in a parent element, its value will be available to all its child elements. However, if a child element declares a variable with the same name, it will override the inherited value within its own scope.
Understanding the scope and inheritance behavior of CSS variables is important for organizing and structuring your code. It allows you to create reusable and modular styles by defining variables at the appropriate levels of your document.
Using CSS Variables
Once you have declared CSS variables, you can reference and use them in your CSS rules. To reference a CSS variable, you use the var()
function followed by the variable name inside parentheses.
Example: Declaring and Using CSS Variables
:root {
--primary-color: #007bff;
}
.button {
background-color: var(--primary-color);
}
In this example, we reference the --primary-color
variable using var(--primary-color)
within the background-color
property of the .button
class. The value of the variable will be applied as the background color for elements with the .button
class.
CSS variables can be updated and changed dynamically using JavaScript. By modifying the value of a CSS variable, you can instantly update the appearance of multiple elements that reference that variable.
Example: Updating CSS Variables with JavaScript
document.documentElement.style.setProperty('--primary-color', '#ff0000');
In this JavaScript code snippet, we use the setProperty()
method to update the value of the --primary-color
variable to #ff0000
(red). Any element that references this variable will immediately reflect the new color.
When referencing CSS variables, you can also provide fallback values. Fallback values are used when the referenced variable is not defined or has an invalid value. To specify a fallback value, you include it as a second argument within the var()
function.
Example: Using Fallback Values with CSS Variables
.text {
color: var(--text-color, #000000);
}
In this example, if the --text-color
variable is not defined or has an invalid value, the fallback value of #000000
(black) will be used as the text color.
Using fallback values provides a way to handle situations where variables may not be available or have unexpected values. It ensures that your styles remain consistent and predictable even if variables are missing or incorrect.
Inheritance and Cascading
CSS variables follow the principles of inheritance and cascading, which are fundamental concepts in CSS. Understanding how inheritance and cascading work with CSS variables is important for creating flexible and maintainable stylesheets.
Inheritance is a mechanism where child elements inherit the values of certain properties from their parent elements. When it comes to CSS variables, child elements can inherit the values of variables defined in their parent elements. This allows you to define variables at a higher level and have them propagate down the document tree.
Inheritance Example
:root {
--font-size: 16px;
}
body {
font-size: var(--font-size);
}
.container {
--font-size: 20px;
}
.container p {
font-size: var(--font-size);
}
The --font-size
variable is defined in the :root
selector with a value of 16px
. The body
element inherits this value and applies it to the font-size
property. However, within the .container
class, the --font-size
variable is overridden with a value of 20px
. The p
elements inside the .container
class will inherit the overridden value of 20px
.
Cascading refers to the process of determining which styles are applied to an element based on the specificity and order of CSS rules. When multiple CSS rules target the same element, the rule with the highest specificity takes precedence. CSS variables also follow the cascading order.
Cascading Example
:root {
--color: blue;
}
.container {
--color: green;
}
.container .button {
color: var(--color);
}
The --color
variable is defined in both the :root
selector and the .container
class. The .button
elements inside the .container
class will use the value of green
for the color
property because the .container
class has a higher specificity than the :root
selector.
It's important to note that CSS variables can be overridden at different levels of the document tree. Variables defined in a more specific selector will take precedence over variables with the same name defined in a less specific selector. This allows for granular control over the values of variables in different parts of your stylesheet.
When overriding CSS variable values, you can also use the !important
declaration to give a variable value the highest priority. However, using !important
should be done sparingly and only when absolutely necessary, as it can make your code harder to maintain and debug.
By leveraging inheritance and cascading with CSS variables, you can create flexible and modular stylesheets. You can define global variables for consistent styling across your document and override them in specific sections or components as needed. This approach promotes code reuse, maintainability, and easier updates to your styles.
Combining with Other CSS Features
CSS variables can be combined with other CSS features to create dynamic and flexible styles. Let's look at how you can use CSS variables with media queries, integrate them with CSS preprocessors, and combine them with CSS animations and transitions.
Media queries let you apply different styles based on the device or viewport characteristics. CSS variables can be used within media queries to create responsive designs that adapt to different screen sizes or device capabilities.
Example: Using CSS Variables with Media Queries
:root {
--font-size: 16px;
}
@media (max-width: 768px) {
:root {
--font-size: 14px;
}
}
.text {
font-size: var(--font-size);
}
The --font-size
variable is initially set to 16px
. However, when the viewport width is less than or equal to 768px
, the variable value is changed to 14px
using a media query. The .text
class uses the --font-size
variable for its font-size
property, automatically adjusting the font size based on the viewport width.
CSS preprocessors like Sass and Less extend the capabilities of CSS by providing features like variables, mixins, and functions. CSS variables can be integrated with CSS preprocessors to create more powerful and reusable styles.
Example: Integrating CSS Variables with Preprocessors
$primary-color: #007bff;
:root {
--primary-color: #{$primary-color};
}
.button {
background-color: var(--primary-color);
}
In this Sass example, the $primary-color
variable is defined using Sass syntax. The --primary-color
CSS variable is then assigned the value of $primary-color
using the #{}
interpolation syntax. The .button
class uses the --primary-color
variable for its background-color
property. This approach lets you use the power of CSS preprocessors while still using CSS variables in your final CSS output.
CSS variables can also be combined with CSS animations and transitions to create dynamic and interactive effects. By updating the values of CSS variables through JavaScript or user interactions, you can trigger smooth animations and transitions.
Example: Combining CSS Variables with Animations and Transitions
:root {
--color: #007bff;
}
.button {
background-color: var(--color);
transition: background-color 0.3s ease;
}
.button:hover {
--color: #ff0000;
}
The .button
class uses the --color
variable for its background-color
property. The transition
property is applied to create a smooth transition effect when the background-color
changes. On hover, the --color
variable is updated to #ff0000
(red), triggering the transition effect.
By combining CSS variables with animations and transitions, you can create engaging and interactive user experiences. You can also use JavaScript to dynamically update CSS variable values based on user actions or other events, enabling real-time style changes and animations.
Combining CSS variables with other CSS features opens up a wide range of possibilities for creating flexible, responsive, and dynamic styles. Whether you're working with media queries, CSS preprocessors, or animations and transitions, CSS variables can be a powerful tool in your styling toolkit.