10.1 Declaring Variables
CSS Variables, also known as CSS Custom Properties, let developers store property values in one place and reuse them throughout the document. This makes CSS more flexible and manageable, especially when working with large projects.
Declaring Variables
CSS variables are declared using two dashes (--) before the variable name. They're usually declared inside the :root
selector to make them available throughout the document.
Syntax:
:root {
--variable-name: value;
--variable-name: value;
}
Example:
In this example, three variables are declared: --main-color
, --secondary-color
, and --font-size
.
:root {
--main-color: #3498db;
--secondary-color: #2ecc71;
--font-size: 16px;
}
10.2 Using Variables
To use variables, the var()
function is applied, which takes the variable name as an argument.
Syntax:
selector {
property: var(--variable-name);
property: var(--variable-name);
}
Example:
This example uses previously declared variables to style the background, text color, and font size of the <body>
element.
body {
background-color: var(--main-color);
color: var(--secondary-color);
font-size: var(--font-size);
}
10.3 Inheritance and Overriding Variables
CSS Variables are inherited through the hierarchy of elements. This means if a variable is declared in one element, it will be accessible to its child elements as well. Variables can also be overridden within other selectors.
Example:
In this example, the .header
element overrides the --main-color
variable, and this new variable is applied only to it. Meanwhile, the .footer
element uses the variable value declared in :root
.
<div class="header">Header</div>
<div class="footer">Footer</div>
:root {
--main-color: #3498db;
}
.header {
--main-color: #e74c3c;
background-color: var(--main-color);
}
.footer {
background-color: var(--main-color);
}
10.4 Benefits of Using CSS Variables
1. Simplifying Style Management:
Variables allow you to change a property value in one place, and this change is automatically applied wherever the variable is used. It's especially useful for theming and maintaining consistent styling.
2. Improving Code Readability and Maintenance:
Using variables makes CSS code more readable and understandable, as they can be used to describe values such as colors and sizes that might have semantic meanings (e.g., --main-color
instead of #3498db
).
3. Dynamic Style Updates:
Variables can be changed dynamically using JavaScript, enabling the creation of more interactive and dynamic user interfaces.
GO TO FULL VERSION