Variables in CSS help you reuse colors, sizes, or other values easily. They make changing styles faster and keep your code neat.
0
0
Using variables in CSS
Introduction
When you want to use the same color in many places on your website.
When you need to keep font sizes consistent across different sections.
When you want to quickly update a style like a background color without searching all your CSS.
When you want to create themes that can change colors or fonts easily.
When you want to avoid repeating the same value multiple times in your CSS.
Syntax
CSS
:root {
--variable-name: value;
}
selector {
property: var(--variable-name);
}Variables start with two dashes -- and are usually defined inside :root for global use.
Use var(--variable-name) to apply the variable value.
Examples
This sets a blue color variable and uses it as the background color for the whole page.
CSS
:root {
--main-color: #3498db;
}
body {
background-color: var(--main-color);
}Defines a padding size variable and applies it to a container element.
CSS
:root {
--padding-size: 1.5rem;
}
.container {
padding: var(--padding-size);
}Stores a font family in a variable and uses it for all h1 headings.
CSS
:root {
--font-stack: 'Arial', sans-serif;
}
h1 {
font-family: var(--font-stack);
}Sample Program
This example shows how to define variables for colors and padding, then use them in the page styles. Changing the variable values in :root updates the whole page easily.
CSS
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>CSS Variables Example</title> <style> :root { --primary-color: #2ecc71; --text-color: #333333; --padding: 1rem; } body { background-color: var(--primary-color); color: var(--text-color); font-family: Arial, sans-serif; padding: var(--padding); margin: 0; } h1 { font-size: 2rem; margin-bottom: var(--padding); } p { font-size: 1rem; line-height: 1.5; } </style> </head> <body> <h1>Welcome to CSS Variables</h1> <p>This page uses variables to keep colors and spacing consistent.</p> </body> </html>
OutputSuccess
Important Notes
Variables are case-sensitive, so --Main-Color and --main-color are different.
If a variable is not defined, the browser ignores it and uses the default or nothing.
You can override variables inside specific selectors to create themes or variations.
Summary
CSS variables store reusable values like colors and sizes.
Define variables inside :root for global use.
Use var(--variable-name) to apply the variable value in styles.