CSS variables (officially known as Custom Properties) are reusable values defined with two dashes (--) that make your CSS code incredibly efficient and much easier to maintain.
var() function to apply these variables anywhere in your CSS.Syntax:
property: var(--custom-name, fallback-value);
| Parameter | Description |
|---|---|
--custom-name |
(Required) The name of the custom property. It must start with two dashes (--). It is case-sensitive! |
fallback-value |
(Optional) A backup value used if the custom property is not defined or is invalid. |
Variables are usually declared inside the :root pseudo-class. The :root selector matches the document's root element (the <html> tag), meaning variables defined here are "global" and can be accessed by any element on the page.
<style>
/* Step 1: Define the variables globally */
:root {
--main-bg-color: lightblue;
--main-text-color: navy;
}
/* Step 2: Use the variables */
body {
background-color: var(--main-bg-color);
color: var(--main-text-color);
}
</style>
<h1>IntricateDevo Variables</h1>
<p>Powered by CSS variables!</p>
Variables are perfect for styling components like buttons. By assigning variables for background, text, and padding, you can easily change the theme of your entire website simply by modifying the :root block.
<style>
:root {
--button-bg: navy;
--button-text: white;
--button-padding: 15px 30px;
--button-radius: 8px;
--hover-bg: lightblue;
--hover-text: navy;
}
.btn {
background-color: var(--button-bg);
color: var(--button-text);
padding: var(--button-padding);
border-radius: var(--button-radius);
transition: 0.3s;
}
.btn:hover {
background-color: var(--hover-bg);
color: var(--hover-text);
}
</style>
<button class="btn">Primary Button</button>
In this example:
:root defines variables like --button-bg and --hover-bg.You can also store measurements (like pixels or percentages) in variables to enforce a consistent spacing system across your design.
<style>
:root {
/* Centralized spacing variable */
--spacing: 20px;
}
.box {
/* Applying the spacing variable to margin */
margin: var(--spacing);
}
</style>
<div class="container">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
</div>
In this example:
:root defines --spacing to set uniform spacing between boxes.--spacing value in :root instantly adjusts the margin for all .box elements simultaneously.:root: Declare your global variables within the :root selector. This ensures they are accessible to every element throughout your entire stylesheet.--primary-color or --base-padding) to greatly enhance readability and maintainability for other developers.Local Override Example:
:root {
--text-color: black;
}
/* Overrides the variable ONLY inside the .dark-mode container */
.dark-mode {
--text-color: white;
}
Which selector is best practice for defining global CSS variables that you want to be accessible anywhere in your document?