How to Use Variables in CSS and Streamline Your Styling

Cascading Style Sheets (CSS) has rapidly evolved over the past 5 years with the introduction of variables, improving Upon CSS’s reputation for being an unscalable language.

CSS variables open up an entire new dimension of possibilities:

CSS variable adoption rates across browsers in 2023

Data source: CanIUse, 2023

With over 90% global adoption, variables now provide a reliable way to better architect CSS. This guide will teach you how to utilize them to their full potential.

Anatomy of a CSS Variable

Before jumping into examples, let’s break down the syntax:

/* Declaration */
--variable-name: value;

/* Usage */
var(--variable-name); 

That covers the basics! But there’s more you need to know:

Types of Scoping

  1. Global (:root) – Accessible everywhere
  2. Local (custom selectors) – Accessible in component

Specificity

Just like other CSS, source order and specificity trump when declaring variables.

Now, let‘s see variables in action for real world use cases.

Declaring Global and Local Variables

Global variables can be declared on the :root pseudo-class:

:root {
  --brand-color: #4267B2;
  --font-size-basic: 16px;
}

While local variables are scoped to a selector:

.banner {
  --bg-gradient: linear-gradient(#D934C3, #17EAD9); 
}

The difference is that --bg-gradient only exists within .banner and its children.

Diagram showing local variable on parent component inherited by children

Some best practices for naming variables:

✅ Descriptive names
✅ Consistent conventions (e.g. prefixes)
❌ No spacing or dashes

Now we can apply these variables to property values:

section {
  /* Global */
  font-size: var(--font-size-basic); 

  /* Local */
  background: var(--bg-gradient); 
}

Much more DRY!

Common Use Case Examples

CSS variables unlock a whole multitude of use cases. Let‘s walk through some popular examples.

Color Palettes

:root {
  /* Primary */
  --marine-blue: #023E5A;

  /* Secondary */
  --pale-green: #C8F4B7; 
}

header {
  background: var(--marine-blue);
  color: var(--pale-green);
}

Now updating brand colors is a breeze across all context!

Typography Settings

:root {
  --font-family: "Poppins";
  --font-size-heading: 2rem;
}

h2 {
  font-family: var(--font-family);
  font-size: var(--font-size-heading);  
} 

Sam‘s for type consistency.

Component Themes

.alert {
  --bg-color: #F8D7DA;
  --text-color: #721C24;
  --border-color: #F5C6CB;   
}

.alert {
  background-color: var(--bg-color);
  color: var(--text-color);
  border: 1px solid var(--border-color);  
}

Centrally control themes and reduce duplication.

The possibilities are endless!

Invalid Variables & Fallbacks

What if a variable is undefined? We can assign fallback values:

background: var(--bg-color, #FFF);

Now #FFF will render if --bg-color is invalid.

In summary, By architecting systems with variables you can streamline management at scale.

Manipulating Variables with JavaScript

A game-changing aspect of CSS variables is runtime modification with JavaScript.

For example, here is script that saves user‘s theme preference:

// Get CSS custom property 
const currentTheme = document.documentElement.style.getPropertyValue(‘--theme‘);

// Set new property value
function setTheme(theme) {
  document.documentElement.style.setProperty(‘--theme‘, theme); 
}

// Save preference locally
setTheme(preferredTheme);  

We can also create dynamic effects by updating values:

let hue = 0; 

setInterval(() => {
  document.documentElement.style.setProperty(‘--main-hue‘, hue);
  hue++;  
}, 10); 

This cycles color hues for a neat rainbow effect!

By combining the powers of CSS and JavaScript you can create more dynamic interfaces. 🎉

However, for performance ensure……

Debugging Common Variable Issues

As with any new syntax, there are some common hurdles you may face:

Undefined Variables

background: var(--not-defined);

Debug by….

Specificity Conflicts

Watch out for source order winning out:

h1 {
  --color: blue; /* Won‘t work! */
  color: var(--color); 
}

h1 {
  color: red; 
}

Prioritize declarations by….

Benefits for Codebase Health

Beyond better architectures and dynamism, variables also allow us to:

☑️ Improve readability – self documenting code

☑️ Streamline onboarding – less tribal knowledge

☑️ Diff commits clearly – changes become more obvious

☑️ Promote modularity – less dependant components

Adopting variables facilitates sharing, reusabiilty and consistency – principles that serve any growing codebase.

It pays dividends to not only learn but master variables as an integral part of your CSS skillset.

Level Up Your Stylesheets

Congratulations – you now know variables inside out!

Some parting thoughts:

🔑 Use meaningful variable names

🔧 Establish a consistent system

💡 Explore possibilities like dynamic effects

📚 Continue learning with resources like….

Variables open new dimensions for CSS maintainability. Take these lessons and streamline your next project!