Menu

Working with CSS Variables to Enhance Reusability and Flexibility

Working with CSS Variables to Enhance Reusability and Flexibility

CSS Variables, also known as Custom Properties, have become a game-changer in the world of web development. They provide the ability to define values in one place and reuse them throughout your CSS, improving code efficiency and maintainability.

If you're a front-end developer looking to streamline your CSS, improve the flexibility of your designs, and manage themes more effectively, CSS variables are your new best friend. 

In this article, I shall dive deep into CSS variables, explore their syntax, and showcase how they can drastically improve the reusability and flexibility of your CSS. Whether you're new to this concept or looking to deepen your understanding, this article has you covered.

What are CSS variables (Custom properties)?

CSS Variables, also referred to as "Custom Properties," allow you to store values in one place in your CSS and reference them multiple times throughout your stylesheet. This is similar to variables in programming languages. The key difference between CSS variables and traditional preprocessor variables (such as those in Sass or LESS) is that CSS variables are native to the browser and can be manipulated at runtime with JavaScript.

Here's a simple example:

:root {
    --primary-color: #3498db;
    --secondary-color: #2ecc71;
    --font-size: 16px;
}

body {
    font-size: var(--font-size);
    color: var(--primary-color);
}

h1 {
    color: var(--secondary-color);
}

In this example, we've defined three variables --primary-color--secondary-color, and --font-size inside the :root selector. This selector targets the document's root element (typically the <html> tag), making these variables globally accessible across your CSS.

The Benefits of CSS Variables

1. Enhanced reusability

By defining common values like colors, font sizes, or spacing (margin and padding) as variables, you can reuse them throughout your stylesheet without having to remember what your consistent values are. This also means that when you need to update a value, such as changing the primary color, you only need to change it in one place.

2. Improved flexibility

CSS Variables offer dynamic flexibility. Unlike preprocessor variables, CSS Variables can be changed at runtime using JavaScript, allowing for real-time updates to styles based on user interaction or application state. This opens up possibilities for responsive design and theming by combining it with JavaScript.

3. Cleaner and more organized code

Instead of hardcoding values repeatedly, you can store them as variables, making your CSS much cleaner and easier to manage. This also helps reduce the chances of inconsistencies across your design, such as slightly different shades of the same color or inconsistent positioning.

4. Theme management

One of the most powerful uses of CSS variables is in theme management. By defining variables for theme-specific values (e.g., colors, fonts), you can switch between themes by simply updating these variables, without having to rewrite your entire stylesheet.

Common Use Cases for CSS Variables

Now that you understand the basics and know a few of the benefits, let's explore some practical ways to use CSS variables in your projects.

1. Color schemes

CSS Variables make it incredibly easy to manage color schemes across large projects. For example, you can define a color palette once and reuse it everywhere, which simplifies updates to your design.

:root {
    --background-color: #f4f4f9;
    --text-color: #333;
    --accent-color: #e74c3c;
}

body {
    background-color: var(--background-color);
    color: var(--text-color);
}

a {
    color: var(--accent-color);
}

To change the site's color scheme, you only need to update the values of --background-color, --text-color, and --accent-color one time and don't have to worry about the potentially thousands of other lines of CSS.

2. Responsive design

You can use CSS Variables to manage breakpoints or adjust layouts dynamically. For example:

:root {
    --spacing: 16px;
}

@media (min-width: 768px) {
    :root {
        --spacing: 24px;
    }
}

.container {
    padding: var(--spacing);
}

In this example, the --spacing variable adjusts automatically when the viewport width exceeds 768px. This approach keeps your breakpoints in sync without duplicating code.

3. Font sizes and typography

Another popular use case is typography. You can set base font sizes or scale them dynamically depending on the screen size:

:root {
    --font-size: 1rem;
}

@media (min-width: 768px) {
    :root {
        --font-size: 1.125rem;
    }
}

body {
    font-size: var(--font-size);
}

This allows for an elegant approach to responsive typography, automatically adjusting font sizes for different devices.

4. Light and dark modes

With CSS Variables, creating light and dark modes becomes extremely easy. Define your color variables in the :root selector and switch between light and dark mode using a simple class toggle.

:root {
    --background-color: #fff;
    --text-color: #000;
}

body.dark-mode {
    --background-color: #121212;
    --text-color: #f4f4f4;
}

body {
    background-color: var(--background-color);
    color: var(--text-color);
}

You can then switch themes by adding or removing the dark-mode class on the <body> element.

CSS Variables vs. Preprocessors: What’s the Difference?

You might be wondering how CSS Variables differ from variables in preprocessors like Sass or LESS. Here are some key differences:

Scope: Preprocessor variables are static and scoped to the file in which they're declared. CSS Variables, however, can be scoped to any selector, and their values can be modified at runtime.

Runtime Modifications: CSS Variables can be updated via JavaScript after the page has loaded, whereas Sass or LESS variables are processed before the CSS is compiled, making them static.

Browser Support: While most modern browsers support CSS Variables, you may need to provide fallbacks for older browsers. Preprocessor variables are widely supported as the processing is done before the code reaches the browser.

Working with CSS Variables and JavaScript

One of the most exciting aspects of CSS Variables is that they can be manipulated in real-time with JavaScript, adding new levels of interactivity and customization.

Here’s how you can dynamically change the value of a CSS Variable using JavaScript:

<button onclick="changeTheme()">Toggle Theme</button>

<script>
    function changeTheme() {
        document.documentElement.style.setProperty('--primary-color', '#e74c3c');
    }
</script>

In this example, when the user clicks the button, the --primary-color variable is updated to a new value, changing the appearance of the page without reloading or updating the CSS file.

Best Practices for Using CSS Variables

To make the most of CSS Variables, here are a few best practices that you can follow:

Use meaningful names: Give your variables descriptive names that clearly convey their purpose. Instead of --color1, use --primary-color.

Define variables in :root: This makes your variables globally available, which is useful for consistent styling.

Fallback values: Always provide fallback values for browsers that don’t support CSS Variables. You can do that with the following:

color: var(--primary-color, #3498db); /* Fallback color */

Conclusion

CSS variables are a powerful tool that significantly enhances the reusability and flexibility of your stylesheets. Whether you're creating a responsive design, managing a theme, or dynamically updating styles with JavaScript, CSS Variables allow for greater control and organization.

By implementing CSS Variables in your projects, you'll not only streamline your development process but also make your code easier to maintain and more adaptable to future design changes.

Walter G. author of blog post
Walter Guevara is a Computer Scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.

Get the latest programming news directly in your inbox!

Have a question on this article?

You can leave me a question on this particular article (or any other really).

Ask a question

Community Comments

No comments posted yet
Ad Unit

Current Poll

Total Votes:
Q:
Submit

Add a comment