0
0
CSSmarkup~15 mins

Declaring variables in CSS - Deep Dive

Choose your learning style9 modes available
Overview - Declaring variables
What is it?
Declaring variables in CSS means creating reusable names for values like colors, sizes, or fonts. These names store information that you can use throughout your stylesheets. Instead of repeating the same value many times, you use the variable name. This makes your CSS easier to read and update.
Why it matters
Without CSS variables, you would have to change every instance of a color or size manually if you want to update your design. This is slow and error-prone. Variables let you change one place and update your whole website’s look instantly. This saves time and reduces mistakes, especially on big projects.
Where it fits
Before learning CSS variables, you should understand basic CSS syntax and how properties and values work. After mastering variables, you can learn about advanced CSS features like custom properties with JavaScript, theming, and responsive design using variables.
Mental Model
Core Idea
CSS variables are named containers that hold values you can reuse and change easily across your styles.
Think of it like...
Think of CSS variables like labels on jars in your kitchen. Instead of remembering what’s inside each jar, you just read the label. If you want to change the spice, you only change the jar’s content, not every recipe that uses it.
┌─────────────────────────────┐
│ :root {                    │
│   --main-color: #3498db;   │
│   --padding: 1rem;         │
│ }                         │
│                           │
│ .button {                 │
│   background: var(--main-color); │
│   padding: var(--padding); │
│ }                         │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationWhat are CSS variables
🤔
Concept: Introducing the idea of CSS variables as named values.
CSS variables, also called custom properties, start with two dashes (--) and are usually declared inside a selector like :root. For example, --main-color: #3498db; stores a blue color. You use them with the var() function, like color: var(--main-color);.
Result
You can write CSS that uses variable names instead of repeating values.
Understanding that CSS variables are just names for values helps you see how they simplify styling and make your code cleaner.
2
FoundationDeclaring variables in :root
🤔
Concept: Using the :root selector to declare global variables.
The :root selector targets the top-level element of the page. Declaring variables here makes them available everywhere. For example: :root { --font-size: 1.2rem; --color-primary: #ff6347; } Now any CSS rule can use var(--font-size) or var(--color-primary).
Result
Variables declared in :root can be used anywhere in your CSS.
Knowing that :root is the global scope for CSS variables helps you organize your styles and reuse values consistently.
3
IntermediateUsing variables inside selectors
🤔Before reading on: Do you think CSS variables can only be used in colors, or can they be used for any CSS property? Commit to your answer.
Concept: CSS variables can store any value, not just colors.
You can use CSS variables for sizes, fonts, spacing, shadows, and more. For example: :root { --spacing: 2rem; --shadow: 0 2px 5px rgba(0,0,0,0.3); } .card { padding: var(--spacing); box-shadow: var(--shadow); } This makes your styles flexible and consistent.
Result
Variables can control many style aspects, making design changes easier.
Understanding that variables are not limited to colors opens up many possibilities for dynamic and maintainable CSS.
4
IntermediateOverriding variables locally
🤔Before reading on: If you declare a variable inside a specific selector, do you think it changes globally or only inside that selector? Commit to your answer.
Concept: Variables can be redefined inside any selector to change their value locally.
For example: :root { --main-color: blue; } .header { --main-color: red; color: var(--main-color); } .footer { color: var(--main-color); } Here, .header text is red, but .footer text stays blue because the variable is overridden only inside .header.
Result
You can customize styles in parts of your page without affecting others.
Knowing that CSS variables follow normal CSS rules of inheritance and scope helps you create flexible themes and components.
5
IntermediateFallback values with var()
🤔Before reading on: What do you think happens if a variable is not defined? Does the browser ignore the property or use a default? Commit to your answer.
Concept: The var() function can take a fallback value if the variable is missing.
Syntax: var(--variable-name, fallback-value) Example: color: var(--text-color, black); If --text-color is not set, the browser uses black instead. This prevents broken styles when variables are missing.
Result
Your CSS becomes more robust and avoids errors from missing variables.
Understanding fallback values helps you write safer CSS that works even if variables are not defined.
6
AdvancedVariables and CSS inheritance
🤔Before reading on: Do CSS variables inherit like normal CSS properties or behave differently? Commit to your answer.
Concept: CSS variables inherit through the DOM tree, but their values depend on where they are declared or overridden.
Variables declared on :root are inherited by all elements. Variables declared on a specific element override inherited ones for that element and its children. This inheritance allows dynamic theming by changing variables on containers. Example: .section { --bg-color: lightgray; } .section .text { background-color: var(--bg-color); } Changing --bg-color on .section changes all nested .text backgrounds.
Result
You can create themes or style variations by changing variables on parent elements.
Knowing how variables inherit helps you build scalable and modular CSS architectures.
7
ExpertPerformance and limitations of CSS variables
🤔Before reading on: Do you think CSS variables are processed at compile time or runtime by the browser? Commit to your answer.
Concept: CSS variables are resolved at runtime, which affects performance and behavior.
Unlike preprocessor variables (like in Sass), CSS variables are handled by the browser when rendering the page. This means they can change dynamically with JavaScript or media queries. However, excessive use or complex overrides can slow rendering. Also, CSS variables cannot be used in some places like media query conditions or property names. Example limitation: @media (min-width: var(--breakpoint)) { ... } // Not supported Understanding these limits helps you use variables wisely.
Result
You gain insight into when and how to use CSS variables for best performance and compatibility.
Knowing that CSS variables are dynamic and runtime-resolved explains their power and constraints in real projects.
Under the Hood
CSS variables are stored as custom properties on elements in the DOM. When the browser renders a page, it looks up the variable value starting from the element itself and moving up the DOM tree until it finds a declaration. The var() function is replaced with the resolved value during style computation. This happens every time the style is recalculated, allowing dynamic changes.
Why designed this way?
CSS variables were designed to be dynamic and live in the DOM to enable runtime changes without recompiling CSS. This allows themes, user preferences, and responsive designs to update styles instantly. Earlier preprocessors required rebuilding CSS files, which was slow and static. The tradeoff is some limitations in where variables can be used.
┌───────────────┐
│ Element       │
│ ┌───────────┐ │
│ │ --color:  │ │
│ │ red       │ │
│ └───────────┘ │
└─────┬─────────┘
      │ inherits
┌─────▼─────────┐
│ Parent Element│
│ ┌───────────┐ │
│ │ --color:  │ │
│ │ blue      │ │
│ └───────────┘ │
└───────────────┘

When var(--color) is used on Element, browser uses 'red' from Element, else 'blue' from Parent.
Myth Busters - 4 Common Misconceptions
Quick: Do CSS variables work exactly like variables in Sass or Less? Commit to yes or no.
Common Belief:CSS variables behave the same as preprocessor variables like in Sass or Less.
Tap to reveal reality
Reality:CSS variables are dynamic and resolved by the browser at runtime, while preprocessor variables are replaced during build time.
Why it matters:Confusing these leads to expecting CSS variables to work in places they cannot, like media queries, causing bugs and frustration.
Quick: If you change a CSS variable with JavaScript, does the page update automatically? Commit to yes or no.
Common Belief:Changing a CSS variable in JavaScript requires reloading the page to see the effect.
Tap to reveal reality
Reality:CSS variables update styles immediately when changed via JavaScript, without page reload.
Why it matters:Knowing this enables dynamic theming and interactive style changes, improving user experience.
Quick: Do CSS variables have global scope by default? Commit to yes or no.
Common Belief:All CSS variables declared anywhere are global and affect the whole page.
Tap to reveal reality
Reality:Variables are scoped to the element they are declared on and inherited by children, so local overrides only affect parts of the page.
Why it matters:Misunderstanding scope can cause unexpected style conflicts or difficulty in managing themes.
Quick: Can CSS variables be used inside media query conditions? Commit to yes or no.
Common Belief:You can use CSS variables anywhere in CSS, including media queries.
Tap to reveal reality
Reality:CSS variables cannot be used inside media query conditions; they only work in property values.
Why it matters:Trying to use variables in media queries causes styles to break or be ignored, leading to layout issues.
Expert Zone
1
CSS variables can be animated with transitions and keyframes, enabling smooth dynamic effects that preprocessors cannot achieve.
2
Variables declared on shadow DOM roots are scoped to that shadow tree, allowing encapsulated styling in web components.
3
Using variables with calc() allows complex dynamic calculations, but beware of browser support and performance impacts.
When NOT to use
Avoid CSS variables when you need to use values in places they are unsupported, like media query conditions or property names. Use preprocessors like Sass for static values that do not change at runtime. Also, for very simple projects, variables might add unnecessary complexity.
Production Patterns
In production, CSS variables are used for theming systems where colors, fonts, and spacing change based on user preferences or modes (dark/light). They enable component libraries to be customizable without rewriting CSS. Variables combined with JavaScript allow runtime style adjustments for accessibility or personalization.
Connections
JavaScript Variables
Both store values that can be reused and changed dynamically.
Understanding CSS variables as runtime values helps bridge styling with JavaScript-driven interactivity and dynamic UI updates.
Environment Variables in DevOps
Both provide a way to configure behavior without changing code directly.
Knowing how CSS variables configure styles like environment variables configure software helps appreciate the power of separation between configuration and logic.
Functional Programming Constants
CSS variables act like constants that can be overridden in scopes, similar to how constants behave in functional programming with lexical scoping.
Recognizing this pattern clarifies how CSS variable scope and inheritance work, improving debugging and design.
Common Pitfalls
#1Using variables without declaring them first.
Wrong approach:.button { color: var(--undefined-color); }
Correct approach::root { --undefined-color: #333; } .button { color: var(--undefined-color); }
Root cause:Forgetting to declare variables causes the browser to ignore the property or use fallback, leading to missing styles.
#2Trying to use CSS variables inside media query conditions.
Wrong approach:@media (min-width: var(--breakpoint)) { body { background: red; } }
Correct approach::root { --breakpoint: 600px; } @media (min-width: 600px) { body { background: red; } }
Root cause:CSS variables are not supported in media query conditions because they are resolved at runtime, but media queries are evaluated earlier.
#3Overriding variables globally unintentionally.
Wrong approach::root { --color: blue; } body { --color: red; } h1 { color: var(--color); }
Correct approach::root { --color: blue; } section { --color: red; } section h1 { color: var(--color); } body h1 { color: var(--color); }
Root cause:Declaring variables on broad selectors like body changes them globally, causing unexpected style changes.
Key Takeaways
CSS variables are named values that make your styles reusable and easier to update.
They are declared with --name syntax and used with var(--name), usually globally in :root.
Variables inherit and can be overridden locally, enabling flexible theming and component styling.
CSS variables are resolved at runtime, allowing dynamic changes but limiting usage in some CSS features.
Understanding their scope, inheritance, and limitations helps you write maintainable and powerful CSS.