The Power of CSS Variables: Writing More Maintainable Styles

The Power of CSS Variables: Writing More Maintainable Styles
Photo by Pankaj Patel / Unsplash

Simplify Your CSS and Take Control of Your Web Design


CSS variables, also known as custom properties, are a powerful feature that allows you to store values in reusable variables directly within your CSS. They simplify your code, make it more maintainable, and enable easy theming. This guide will explore CSS variables, how to use them, and why they are essential for writing scalable and maintainable styles.


What are CSS Variables?

CSS variables allow you to define reusable values (such as colours, fonts, and sizes) and reference them throughout your CSS. They follow a naming convention where the variable name starts with -- and can be accessed using the var() function.

Syntax Example:

:root {
  --primary-color: #3498db;
  --font-size-large: 2rem;
}

h1 {
  color: var(--primary-color);
  font-size: var(--font-size-large);
}
  • :root defines variables globally (available throughout the whole document).
  • var(--primary-color) references the CSS variable in the h1 styles.

Why Use CSS Variables?

  1. Maintainability:
    • Update values in one place, and it reflects everywhere in the project.
    • This reduces redundancy and makes refactoring easier.
  2. Theming Capabilities:
    • CSS variables make it easy to switch between light and dark modes or any other themes by changing a few values dynamically.
  3. Scope Flexibility:
    • Variables can be scoped to specific elements, reducing style conflicts.
  4. Dynamic Updates:
    • CSS variables can be manipulated using JavaScript, making them perfect for interactive and dynamic designs.

How to Define and Use CSS Variables

Global Scope Variables using :root

Use :root to define variables at the top of your CSS file, so they are available throughout the whole document.

:root {
  --primary-color: #1abc9c;
  --secondary-color: #2c3e50;
  --base-font-size: 1rem;
}

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

Scoped CSS Variables

You can define variables within a specific element, and they will only apply to that element and its children.

.card {
  --card-bg-color: #f5f5f5;
  background-color: var(--card-bg-color);
  padding: 16px;
}

Fallback Values with var()

If a CSS variable isn’t defined, you can provide a fallback value within the var() function.

button {
  /* Default to #3498db if --button-bg isn't set */
  background-color: var(--button-bg, #3498db);                     
}

Theming with CSS Variables

CSS variables make it simple to switch between light and dark modes.

Light and Dark Mode Example:

:root {
  --bg-color: #ffffff;
  --text-color: #333333;
}

[data-theme="dark"] {
  --bg-color: #1e1e1e;
  --text-color: #f5f5f5;
}

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

Using JavaScript, you can toggle between themes dynamically:

const toggleTheme = () => {
  document.documentElement.dataset.theme =
    document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
};

document.querySelector('#theme-toggle').addEventListener('click', toggleTheme);

Using CSS Variables with JavaScript

CSS variables can be read and updated dynamically using JavaScript, giving you more flexibility for interactive designs.

Example: Dynamic Updates with JavaScript

:root {
  --primary-color: #3498db;
}

button {
  background-color: var(--primary-color);
}
const toggleColor = () => {
  document.documentElement.style.setProperty('--primary-color', '#e74c3c');
};

document.querySelector('#color-change').addEventListener('click', toggleColor);

In this example, clicking the button changes the primary color of your site dynamically.


Best Practices for Using CSS Variables

    • Define colors, fonts, and spacing variables logically to make them easier to maintain.
  1. Use Meaningful Names:
    • Avoid vague names like --main-color; instead, use specific ones like --button-bg-color.
  2. Provide Fallbacks:
    • Use fallback values to prevent errors if a variable is missing.
  3. Modular CSS:
    • Scope variables to components when possible to avoid unintended side effects.

Group Related Variables Together:

:root {
  /* Colors */
  --primary-color: #3498db;
  --secondary-color: #2c3e50;

  /* Fonts */
  --font-primary: 'Roboto', sans-serif;
  --font-secondary: 'Open Sans', sans-serif;
}

Limitations of CSS Variables

  1. Browser Compatibility:
    • CSS variables are not supported in older browsers (e.g., IE11). However, modern browsers like Chrome, Firefox, Edge, and Safari fully support them.
  2. Static Limitations:
    • Variables cannot be used inside media queries or calculated within CSS (though you can use JavaScript to achieve this).

Conclusion

CSS variables are a powerful tool for writing more maintainable and scalable styles. They enable reusability, easy theming, and dynamic updates—all while keeping your code clean and DRY (Don’t Repeat Yourself). By adopting CSS variables, you’ll simplify your workflow and make your CSS more manageable for future projects.

Start using CSS variables today, and take control of your web design like a pro! 🎨


Happy Styling! 🎉