CSS Variables (Custom Properties)
Learn CSS through interactive, bite-sized lessons. Style beautiful websites and master modern CSS techniques.
Start CSS Journey →CSS Variables, also known as Custom Properties, are entities that allow you to store specific values to be reused throughout your stylesheet. They provide a way to create more maintainable and flexible CSS code.
Defining CSS Variables
To define a CSS variable, use double dashes (--) followed by the variable name. Variables are typically declared within a selector, often the :root pseudo-class for global scope:
:root {
--primary-color: #3498db;
--font-size: 16px;
}
Using CSS Variables
To use a CSS variable, employ the var() function:
body {
background-color: var(--primary-color);
font-size: var(--font-size);
}
Benefits of CSS Variables
- Improved code maintainability
- Easy theme switching
- Reduced repetition in stylesheets
- Dynamic value changes with JavaScript
Fallback Values
You can provide fallback values in case a variable is not defined:
p {
color: var(--text-color, #333);
}
Scope and Inheritance
CSS Variables follow the cascading nature of CSS. They can be redefined within different selectors, creating a scoped value:
.button {
--button-color: blue;
background-color: var(--button-color);
}
.button.danger {
--button-color: red;
}
JavaScript Integration
CSS Variables can be manipulated using JavaScript, allowing for dynamic style changes:
document.documentElement.style.setProperty('--primary-color', '#ff0000');
Browser Support
CSS Variables are supported in all modern browsers. For older browsers, consider using a polyfill or providing fallback values.
Best Practices
- Use meaningful and descriptive variable names
- Organize variables logically, grouping related properties
- Consider using a naming convention, such as BEM, for larger projects
- Provide fallback values for critical styles
Related Concepts
To further enhance your CSS skills, explore these related topics:
By mastering CSS Variables, you'll be able to create more flexible and maintainable stylesheets, improving your overall web development workflow.