0
0
CSSmarkup~15 mins

Using variables in CSS - Deep Dive

Choose your learning style9 modes available
Overview - Using variables
What is it?
CSS variables are custom names for values you want to reuse throughout your styles. They let you store colors, sizes, or any CSS value once and use them many times. This makes your code easier to read and update. Variables start with two dashes and are accessed with a special syntax.
Why it matters
Without CSS variables, you would have to repeat the same values everywhere. Changing a color or size would mean hunting down every place it appears, which is slow and error-prone. Variables save time and reduce mistakes, making websites easier to maintain and update.
Where it fits
Before learning CSS variables, you should know basic CSS syntax and how to write selectors and properties. After mastering variables, you can learn advanced CSS features like calc(), media queries, and theming with variables.
Mental Model
Core Idea
CSS variables are like labels for values that you can reuse and change in one place to update many styles at once.
Think of it like...
Imagine a label on a jar in your kitchen. Instead of remembering the recipe every time, you just grab the jar labeled 'sugar' whenever you need sugar. If you change the jar's content, all recipes using that jar get the new sugar automatically.
┌─────────────────────────────┐
│ :root {                    │
│   --main-color: #3498db;   │
│   --padding: 1rem;         │
│ }                          │
│                             │
│ .button {                  │
│   background: var(--main-color);
│   padding: var(--padding); │
│ }                          │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationWhat are CSS variables
🤔
Concept: Introduction to CSS variables and their syntax.
CSS variables are custom properties that start with two dashes, like --main-color. You define them inside a selector, often :root, which means they are global. To use a variable, you write var(--variable-name) where you want the value.
Result
You can write --main-color: #3498db; once and use var(--main-color) anywhere in your CSS.
Understanding that CSS variables are just named values helps you see how they simplify repeating styles.
2
FoundationDefining and using variables
🤔
Concept: How to declare variables and apply them in CSS rules.
Define variables inside :root for global use: :root { --font-size: 1.2rem; --primary-color: #e74c3c; } Use them in selectors: h1 { font-size: var(--font-size); color: var(--primary-color); }
Result
The h1 text will have font size 1.2rem and color #e74c3c, controlled by variables.
Knowing how to declare and use variables lets you control many styles from one place.
3
IntermediateVariable scope and inheritance
🤔Before reading on: Do you think CSS variables are global or can be local to selectors? Commit to your answer.
Concept: Variables can be scoped to selectors, affecting only their children.
Variables defined in :root are global. But you can define variables inside any selector: .container { --bg-color: lightgray; } .child { background-color: var(--bg-color); } Only elements inside .container see --bg-color; outside elements do not.
Result
Elements inside .container use lightgray background; outside elements do not have that variable.
Understanding scope helps you create modular styles and avoid conflicts.
4
IntermediateFallback values with variables
🤔Before reading on: What happens if a variable is missing? Does CSS break or use a default? Commit your guess.
Concept: You can provide fallback values if a variable is not defined.
Use var(--variable, fallback) syntax: button { color: var(--button-color, black); } If --button-color is missing, black is used instead.
Result
The button text color is black if the variable is not set, preventing broken styles.
Fallbacks make your CSS more robust and prevent missing variable errors.
5
IntermediateUsing variables with calc()
🤔
Concept: Combine variables with calculations for dynamic values.
You can use variables inside calc() to do math: :root { --base-size: 16px; } p { font-size: calc(var(--base-size) * 1.5); } This sets font size to 24px (16 * 1.5).
Result
Paragraph text size adjusts dynamically based on the variable value.
Combining variables with calc() allows flexible and responsive styling.
6
AdvancedChanging variables with JavaScript
🤔Before reading on: Can CSS variables be changed after page load? Guess yes or no.
Concept: CSS variables can be updated dynamically using JavaScript.
Use JavaScript to change variables: const root = document.documentElement; root.style.setProperty('--main-color', 'purple'); This changes all uses of --main-color to purple immediately.
Result
The page updates colors or sizes live without reloading.
Knowing variables are live values lets you create interactive themes and effects.
7
ExpertVariable inheritance and cascade surprises
🤔Before reading on: Do variables behave like normal CSS properties in inheritance and cascade? Commit your answer.
Concept: CSS variables follow the cascade and inheritance but can cause unexpected results if misunderstood.
Variables inherit from parents but can be overridden locally. If a variable is undefined in a scope, it looks up the chain. However, if a variable is missing and no fallback is given, the property using it becomes invalid. Example: .parent { --color: red; } .child { color: var(--color); } If .child overrides --color with nothing, color breaks. This subtlety can cause bugs.
Result
Styles may break silently if variables are missing or overridden incorrectly.
Understanding the cascade and inheritance of variables prevents subtle styling bugs in complex projects.
Under the Hood
CSS variables are stored as custom properties on elements in the browser's style system. When the browser renders, it looks up the variable value starting from the element itself, then up through its ancestors until it finds a definition or uses a fallback. This lookup happens at runtime, allowing dynamic changes. Variables do not create new CSS properties but act as references that the browser replaces before applying styles.
Why designed this way?
CSS variables were designed to be part of the cascade and inheritance model to fit naturally with existing CSS. This allows them to be scoped and overridden like normal properties, giving developers flexible control. Alternatives like preprocessors (Sass variables) are static and compile-time only, lacking runtime flexibility.
Element Styles
┌───────────────┐
│ Element       │
│ ┌───────────┐ │
│ │ --var: x  │ │
│ └───────────┘ │
└─────┬─────────┘
      │ Lookup
      ▼
┌───────────────┐
│ Parent Element │
│ ┌───────────┐ │
│ │ --var: y  │ │
│ └───────────┘ │
└───────────────┘
If not found on element, use parent's value or fallback.
Myth Busters - 4 Common Misconceptions
Quick: Do CSS variables work like programming variables that store values only once? Commit yes or no.
Common Belief:CSS variables are fixed values set once and never change unless you edit the CSS file.
Tap to reveal reality
Reality:CSS variables are live and dynamic; they can be changed at runtime by JavaScript and respond to the cascade and inheritance.
Why it matters:Believing variables are static stops developers from using powerful dynamic theming and interactive styling.
Quick: If a CSS variable is missing, does the browser ignore the whole rule or use a default? Commit your guess.
Common Belief:If a CSS variable is missing, the browser uses a default value automatically.
Tap to reveal reality
Reality:If no fallback is provided and the variable is missing, the entire CSS property becomes invalid and is ignored.
Why it matters:Not providing fallbacks can cause unexpected broken styles that are hard to debug.
Quick: Are CSS variables global by default? Commit yes or no.
Common Belief:CSS variables are always global and cannot be scoped locally.
Tap to reveal reality
Reality:Variables can be scoped to any selector, limiting their effect to that part of the page.
Why it matters:Assuming global scope leads to conflicts and harder-to-maintain styles.
Quick: Do CSS variables behave exactly like normal CSS properties in inheritance? Commit yes or no.
Common Belief:CSS variables inherit exactly like normal CSS properties without exceptions.
Tap to reveal reality
Reality:Variables inherit but missing or overridden variables can cause properties to break, which is different from normal properties that have default values.
Why it matters:Misunderstanding inheritance can cause subtle bugs in complex style sheets.
Expert Zone
1
Variables are resolved at computed style time, meaning their values can depend on the current state of the DOM and cascade, not just static CSS.
2
Using variables inside media queries or pseudo-classes allows creating responsive and stateful designs without duplicating code.
3
Variables can store any CSS value, including complex ones like gradients or shadows, enabling advanced theming.
When NOT to use
Avoid CSS variables when targeting very old browsers that do not support them (e.g., IE11). For static values that never change, simple CSS properties or preprocessors like Sass may be simpler. Also, avoid overusing variables for trivial values as it can make CSS harder to read.
Production Patterns
In production, variables are used for theming (light/dark modes), responsive sizing, and consistent spacing. Teams define variables in :root and override them in component scopes for modularity. JavaScript toggles variables for dynamic themes without reloading pages.
Connections
Programming variables
Similar pattern of naming and reusing values
Understanding programming variables helps grasp CSS variables as reusable named values that can change and be scoped.
Environment variables in operating systems
Both store configuration values accessible by many parts of a system
Knowing environment variables clarifies how CSS variables provide centralized control over style settings.
Supply chain management
Both involve centralized control points that affect many downstream items
Seeing CSS variables like a supply chain helps understand how changing one source value cascades to many dependent styles.
Common Pitfalls
#1Using variables without fallbacks causes broken styles if variable is missing.
Wrong approach:p { color: var(--missing-color); }
Correct approach:p { color: var(--missing-color, black); }
Root cause:Not providing fallback assumes variable is always defined, which is unsafe.
#2Defining variables inside a selector but expecting them to be global.
Wrong approach::root { } .button { --main-color: red; } h1 { color: var(--main-color); }
Correct approach::root { --main-color: red; } h1 { color: var(--main-color); }
Root cause:Misunderstanding variable scope causes unexpected missing values.
#3Trying to use CSS variables in unsupported browsers without fallback.
Wrong approach:body { background: var(--bg-color); } /* no fallback */
Correct approach:body { background: var(--bg-color, white); }
Root cause:Ignoring browser support leads to broken styles on old browsers.
Key Takeaways
CSS variables let you name and reuse values, making styles easier to manage and update.
They follow CSS rules like inheritance and cascade, allowing flexible scoping and overrides.
Fallback values prevent broken styles when variables are missing or undefined.
Variables can be changed dynamically with JavaScript, enabling interactive and themeable designs.
Understanding variable scope and inheritance prevents subtle bugs in complex CSS.