Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Variables in CSS
Variables in CSS are used to store values that can be reused throughout your stylesheet. They allow you to define custom properties with meaningful names and reference them anywhere in your CSS, making your code more maintainable and easier to update.
Syntax
/* Define variables */
:root {
--variable-name: value;
}
/* Use variables */
selector {
property: var(--variable-name);
}
Key Points
- CSS variables are defined with
--prefix - The
:rootselector makes variables globally accessible - Use
var()function to access variable values - Variable names are case-sensitive
Example: Color Variables
The following example demonstrates how to define and use CSS variables for colors −
<!DOCTYPE html>
<html>
<head>
<style>
:root {
--primary-bg-color: #3498db;
--primary-text-color: white;
--secondary-bg-color: #e74c3c;
}
.primary-section {
background-color: var(--primary-bg-color);
color: var(--primary-text-color);
padding: 20px;
margin: 10px 0;
}
.secondary-section {
background-color: var(--secondary-bg-color);
color: var(--primary-text-color);
padding: 20px;
margin: 10px 0;
}
</style>
</head>
<body>
<h1>CSS Variables Demo</h1>
<div class="primary-section">
This section uses primary colors defined as CSS variables.
</div>
<div class="secondary-section">
This section uses secondary colors with the same text color variable.
</div>
</body>
</html>
A blue section with white text and a red section with white text appear on the page, both styled using CSS variables.
Example: Fallback Values
You can provide fallback values in case a variable is not defined −
<!DOCTYPE html>
<html>
<head>
<style>
:root {
--main-font-size: 18px;
}
.text-example {
font-size: var(--main-font-size, 16px);
color: var(--undefined-color, #333);
padding: 15px;
border: 1px solid #ddd;
}
</style>
</head>
<body>
<div class="text-example">
This text uses a defined font-size variable (18px) and falls back to #333 color since --undefined-color is not defined.
</div>
</body>
</html>
Text appears with 18px font size and dark gray color (#333), demonstrating how fallback values work when variables are undefined.
Conclusion
CSS variables provide a powerful way to create reusable values in your stylesheets. They improve code maintainability and make it easy to implement consistent design systems across your website.
Advertisements
