cross icon
WebSimplifying Your Stylesheets with CSS variables

Simplifying Your Stylesheets with CSS variables

7 mins Read
mainImg

Written by

profileImg

Manish Sharma

Front End Developer

Table of contents

Build with Radial Code

Radial Code Enterprise gives you the power to create, deploy and manage sites collaboratively at scale while you focus on your business. See all services.

CSS variables, also known as custom properties, have revolutionized the way developers manage stylesheets by introducing a new level of flexibility and maintainability. In an era where responsive design and theming are crucial, CSS variables offer a powerful tool to streamline these processes. This article delves into the practical applications of CSS variables, demonstrating how they can simplify your stylesheets, enhance readability, and improve the overall efficiency of your web development projects. Whether you're managing complex themes or ensuring consistency across your design system, CSS variables provide a robust solution that every modern developer should master.

Why we should use it?

Some common use cases include: 

  • Theme Management: They make it easy to manage and switch themes by defining color schemes and other stylistic elements as variables.
  • Responsive Design: Variables can be adjusted based on media queries for different screen sizes or orientations.

Key Concepts

1. Declaring CSS Variables

CSS variables are defined using a custom property notation, which starts with two dashes (--), followed by the variable name. They are typically declared within a selector, often the :root pseudo-class for global scope, allowing access throughout the entire document. This setup is ideal for maintaining consistency across your stylesheets. Here’s a basic example:

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

In this example, --primary-color and --font-size are CSS variables that can be reused throughout your stylesheet, making it easy to update styles globally by changing the variable values in one place.

2. Using CSS Variables:

CSS variables are custom variables that you can create and reuse throughout your stylesheet. Here is the basic syntax for defining a custom CSS variable. --css-variable-name css property value; If you want to access that variable, then you would use the var() function.

  • You can use the var()function to access the value of a CSS variable.
body {
    color: var(--primary-color);
    font-size: var(--font-size);
}

3. Benefits of using CSS variables:

  • Maintainability: By defining styles as variables, you can change the value in one place, and it updates everywhere the variable is used. This reduces redundancy and makes it easier to manage large stylesheets.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Maintainability Example</title>
<style>
  :root {
            --primary-color: #3498db;
        }

        .header, .footer {
            background-color: var(--primary-color);
            color: white;
            padding: 10px;
        }

        .button {
            background-color: var(--primary-color);
            border: none;
            color: white;
            padding: 10px 20px;
            cursor: pointer;
        }
</style>
</head>
<body>
<div class="header">Header</div>
<button class="button">Click Me</button>
<div class="footer">Footer</div>
</body>
</html>
  • Readability: Variables can have meaningful names, making the CSS easier to understand and maintain. This clarity helps developers quickly grasp the purpose of each style, improving collaboration and reducing errors.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Readability Example</title>
<style>
  :root {
            --main-bg-color: #f0f0f0;
            --main-text-color: #333;
            --accent-color: #e74c3c;
        }

        body {
            background-color: var(--main-bg-color);
            color: var(--main-text-color);
            font-family: Arial, sans-serif;
        }

        .highlight {
            color: var(--accent-color);
        }
</style>
</head>
<body>
<p>This is a paragraph with <span class="highlight">highlighted text</span></p>
</body>
</html>

In this example, the variables --main-bg-color--main-text-color, and --accent-color have meaningful names that make the CSS easier to understand.

  • Theming: CSS variables simplify the process of creating and managing themes. By adjusting variable values, you can easily switch between themes or update a theme's appearance without altering the entire stylesheet.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Theming Example</title>
<style>
 :root {
            --bg-color: #ffffff;
            --text-color: #000000;
        }

        html[data-theme="dark"] {
            --bg-color: #333333;
            --text-color: #ffffff;
        }

        body {
            background-color: var(--bg-color);
            color: var(--text-color);
            font-family: Arial, sans-serif;
            transition: background-color 0.3s, color 0.3s;
        }

        .theme-toggle {
            margin: 20px;
            padding: 10px 20px;
            cursor: pointer;
        }
</style>
</head>
<body>
<button class="theme-toggle" onclick="toggleTheme()">Toggle Theme</button>
<script>
        function toggleTheme() {
            const currentTheme = document.documentElement.getAttribute("data-theme");
            if (currentTheme === "dark") {
                document.documentElement.removeAttribute("data-theme");
            } else {
                document.documentElement.setAttribute("data-theme", "dark");
            }
        }
    </script>
</body>
</html>
  • Responsive Design: CSS variables can be dynamically adjusted using media queries to create responsive designs that adapt to different screen sizes or orientations. This flexibility allows developers to maintain a consistent look and feel across various devices while optimizing the user experience.

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Design with CSS Variables</title>
<style>
 :root {
            --font-size: 16px;
            --padding: 10px;
        }

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

        @media (min-width: 768px) {
            :root {
                --font-size: 18px;
                --padding: 20px;
            }
        }

        @media (min-width: 1024px) {
            :root {
                --font-size: 20px;
                --padding: 30px;
            }
        }
</style>
</head>
<body>
<p class="theme-toggle">This text and padding will adjust based on the screen size.</p>
</body>
</html>

In this example, the font size and padding are adjusted based on the screen width, ensuring that the design remains user-friendly and visually appealing across different devices.

4. Scope and Inheritance

CSS variables are scoped to the selector in which they are defined, allowing for both global and local usage. When declared in the :root they are globally scoped and can be accessed throughout the entire document, providing a consistent styling approach across all elements. This is particularly useful for defining site-wide themes or common design elements.

Conversely, variables can also be locally scoped within specific selectors, offering flexibility to override global styles for particular sections or components. This dual capability of scope and inheritance makes CSS variables a versatile tool for managing complex stylesheets efficiently, ensuring both consistency and customization where needed.

Example of Global Scoped CSS Variables

Global scoped CSS variables are defined in the :root selector, making them accessible throughout the entire document. This approach is particularly useful for maintaining consistent styling across a website, as changes to a variable's value will automatically propagate wherever the variable is used.

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Global Scoped CSS Variables</title>
<style>
 :root {
            --main-bg-color: #f0f0f0;
            --main-text-color: #333;
            --heading-font: 'Arial', sans-serif;
            --body-font: 'Verdana', sans-serif;
        }
        body {
            background-color: var(--main-bg-color);
            color: var(--main-text-color);
            font-family: var(--body-font);
        }
        h1, h2, h3 {
            font-family: var(--heading-font);
        }
</style>
</head>
<body>
<h1>Welcome to Our Website</h1>
<p>This is a sample paragraph demonstrating the use of global CSS variables for consistent styling.</p>
</body>
</html>

In this example, changing the value of --main-bg-colorin the :root will update the background color of the entire page, demonstrating the power and flexibility of CSS variables.

Example of Locally Scoped CSS Variables

Locally scoped CSS variables offer a powerful way to manage styles within specific sections of your webpage, allowing for greater flexibility and control over individual components. Unlike global variables, which are declared in the :root and affect the entire document, local variables are defined within a specific selector, making them ideal for modular design.

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Global Scoped CSS Variables</title>
<style>
  .container {
            --main-bg-color: lightblue;
            --main-text-color: darkblue;
            background-color: var(--main-bg-color);
            color: var(--main-text-color);
            padding: 20px;
        }

        .container .header {
            --header-bg-color: lightcoral;
            background-color: var(--header-bg-color);
            padding: 10px;
        }

        .container .content {
            --content-bg-color: lightgreen;
            background-color: var(--content-bg-color);
            padding: 10px;
        }
</style>
</head>
<body>
<div class="container">
<div class="header">Header Section</div>
<div class="content">Content Section</div>
</div>
</body>
</html>

In this example, the .containerclass defines local variables for background and text colors, which are then used within its child elements. This approach allows for easy customization and theming of specific sections without affecting the global styles, demonstrating the power and flexibility of CSS variables in creating responsive and maintainable designs.

Conclusion

CSS variables offer a powerful way to enhance the maintainability, readability, and theming capabilities of your stylesheets. By using custom properties, you can easily manage and update styles across your entire project, ensuring consistency and reducing the need for repetitive code. Embracing CSS variables can significantly streamline your development process and improve the overall quality of your web design.

You can dive deeper into any specific aspect of CSS variables and coding from here

cta

Share this

whatsapp
whatsapp
whatsapp
whatsapp
whatsapp

Keep Reading

Stay up to date with all news & articles.

Email address

Copyright @2025. All rights reserved | Radial Code