CSS variables, often referred to as custom properties, offer a centralized way to manage values in your stylesheets. By using the var()
function, you can insert these variable values directly into your CSS, making it more streamlined and manageable. Whether you're applying global or local scope, CSS variables enhance readability and maintainability across your projects.
Introduction to CSS Variables
CSS variables, also called custom properties, let you store values centrally in your CSS. The var()
function is used to insert the value of these variables. Variables can be scoped globally or locally, which means they can be used either throughout the whole document or only within a specific selector.
The syntax for the var()
function is as follows:
var(--custom-name, fallback-value);
--custom-name
: This is a required parameter that must start with two dashes.fallback-value
: This optional parameter is used if the variable isn't found.
Variable names are case-sensitive and must start with two dashes (–).
Global variables are declared inside the :root
selector. This makes them accessible throughout the entire document. For example:
:root {
--main-bg-color: #00ff00;
--main-text-color: #ffffff;
}
You can use these globally scoped variables like this:
body {
background-color: var(--main-bg-color);
color: var(--main-text-color);
}
Local variables are declared within a specific selector, limiting their scope to that selector alone. For example:
button {
--button-color: #0000ff;
color: var(--button-color);
}
CSS variables can handle more than just colors. They provide an efficient way to manage design consistency across a project. For example:
:root {
--main-padding: 16px;
--main-margin: 8px;
}
.container {
padding: var(--main-padding);
margin: var(--main-margin);
}
Modern browsers support CSS variables (var()), including recent versions of Chrome, Edge, Firefox, Safari, and Opera.
Using var() Function
The var()
function simplifies inserting CSS variable values directly into your styles. Here's how to use it effectively:
The basic syntax of the var()
function is:
var(--custom-name, fallback-value);
--custom-name
: This required parameter is the name of the CSS variable and must start with two dashes.fallback-value
: This optional parameter acts as a backup if the variable is not found.
Using Global CSS Variables
First, we declare global variables inside the :root
selector:
:root {
--main-color: #3498db;
--secondary-color: #2ecc71;
}
Now, you can use these variables throughout your CSS:
body {
background-color: var(--main-color);
color: var(--secondary-color);
}
Using Fallback Values
Fallback values ensure your CSS works even when a variable is not defined:
p {
color: var(--text-color, #333);
}
Real-world Scenarios
Consider a situation where the theme of a site changes between light and dark modes:
:root {
--background-color: #fff;
--text-color: #000;
}
[data-theme='dark'] {
--background-color: #000;
--text-color: #fff;
}
body {
background-color: var(--background-color);
color: var(--text-color);
}
Themed Content
This content adapts based on the theme!
Use in Component-Based Design
When handling multiple components, CSS variables ensure design consistency and simplify updates:
:root {
--button-bg: #1abc9c;
--button-text-color: #fff;
}
.button {
background: var(--button-bg);
color: var(--button-text-color);
padding: 10px 20px;
border: none;
border-radius: 5px;
}
Advantages of CSS Variables
CSS variables offer several practical advantages:
- Enhanced readability and maintainability: Define values once as variables and reuse them as needed, eliminating redundancy.
- Easier color scheme updates: Change the value in one place, and the changes are automatically propagated throughout your CSS.
- Efficient responsive design: Define variables for breakpoints and use them in media queries:
:root {
--small-screen: 600px;
--medium-screen: 768px;
--large-screen: 1024px;
}
@media (max-width: var(--small-screen)) {
body {
font-size: 14px;
}
}
- Dynamic style adaptation: Implement theme toggling with variable adjustments:
:root {
--bg-color: #fff;
--text-color: #000;
}
[data-theme='dark'] {
--bg-color: #000;
--text-color: #fff;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
}
- Nuanced design customization: Override variables in child selectors or components:
:root {
--btn-bg: #3498db;
--btn-text: #fff;
}
button {
background-color: var(--btn-bg);
color: var(--btn-text);
}
.dark-mode button {
--btn-bg: #e74c3c;
--btn-text: #000;
}
CSS variables streamline the styling process, leading to more efficient development and quicker adjustments for maintaining modern, dynamic websites.
Practical Examples of CSS Variables
CSS variables have several practical applications, including implementing a dark mode and resetting font and link styles.
Creating a Simple Dark Mode Switch:
- Define variables for light and dark themes:
:root {
--bg-color: #ffffff;
--text-color: #000000;
--link-color: #1a0dab;
}[data-theme='dark'] {
--bg-color: #000000;
--text-color: #ffffff;
--link-color: #8ab4f8;
}
- Apply the variables in your styles:
body {
background-color: var(--bg-color);
color: var(--text-color);
}a {
color: var(--link-color);
}
- Toggle the theme using JavaScript:
<button id="theme-toggle">Toggle Dark Mode</button><script>
const toggleButton = document.getElementById('theme-toggle');
toggleButton.addEventListener('click', () => {
const currentTheme = document.body.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
document.body.setAttribute('data-theme', newTheme);
});
</script>
Resetting Font and Link Styles:
- Define font and link styles:
:root {
--font-family: 'Arial, sans-serif';
--link-color: #1a0dab;
--link-hover-color: #551a8b;
}
- Apply the variables:
body {
font-family: var(--font-family);
}a {
color: var(--link-color);
text-decoration: none;
}a:hover {
color: var(--link-hover-color);
}
CSS variables can also simplify management of complex nested components. For example, to manage padding and margin in card components:
- Define variables for padding and margin:
:root {
--global-padding: 20px;
--global-margin: 10px;
}
- Apply these variables in components:
.card {
padding: var(--global-padding);
margin: var(--global-margin);
background: #fff;
border-radius: 5px;
}.card-content {
padding: var(--global-padding);
}
These examples demonstrate how CSS variables can enhance flexibility and efficiency in web development.
Browser Support and Compatibility
CSS variables are supported by all major modern browsers from the following versions:
- Google Chrome: 49.0+
- Microsoft Edge: 15.0+
- Firefox: 31.0+
- Safari: 9.1+
- Opera: 36.0+
This broad support allows developers to use CSS variables confidently in current web projects. While Internet Explorer does not support CSS variables, modern web development practices often focus on progressive enhancement.
The var()
function includes a fallback mechanism, allowing developers to specify a default value:
p {
color: var(--text-color, #333); /* If --text-color is not defined, defaults to #333 */
}
This feature helps ensure styles render correctly even if specific variables are not defined, adding to the robustness of CSS variable usage.
In summary, CSS variables simplify style management in web development. By defining reusable values with the var()
function, you can improve the readability and maintainability of your stylesheets, allowing for efficient adaptation to various needs.
Elevate your content with Writio – the AI content writer for websites and blogs. This article was crafted by Writio.