Modern websites are expected to deliver consistent visual experiences across different pages, devices, and user interactions. A website may contain dozens of buttons, navigation elements, cards, forms, banners, and other interface components. Although these elements may appear in different sections, they often share common design properties such as brand colors, typography, spacing, border radiuses, shadows, and layout dimensions.
Managing these properties individually can become difficult as a project grows. Imagine a website that uses the same primary blue color across fifty different CSS rules. If the brand color changes, a developer may need to locate and update every occurrence. Missing even a few declarations can produce an inconsistent interface.
CSS Variables, officially known as CSS Custom Properties, provide a practical solution. They allow developers to define reusable values and reference them throughout stylesheets. Instead of repeating the same color, spacing value, or font size, developers can store it once and reuse it wherever necessary.
CSS Custom Properties are particularly useful for building design systems, implementing dark mode, supporting multiple themes, creating configurable components, and maintaining large frontend applications. Unlike traditional preprocessor variables, CSS Custom Properties are available in the browser at runtime, which means their values can change dynamically through stylesheets, JavaScript, user preferences, and responsive conditions.
Understanding CSS Variables is an important step toward writing maintainable, reusable, and scalable frontend code.
Continue Reading
1. What Are CSS Variables and Custom Properties?
CSS Custom Properties are named values defined within CSS and reused through the var() function. They are commonly called CSS Variables because they behave similarly to variables in programming languages, although their behavior follows the CSS cascade and inheritance model.
A custom property begins with two hyphens followed by a name.
For example:
:root {
--primary-color: #2563eb;
--secondary-color: #64748b;
--text-color: #1e293b;
--page-background: #f8fafc;
}The values can then be reused in other declarations.
button {
background-color: var(--primary-color);
color: white;
}
body {
color: var(--text-color);
background-color: var(--page-background);
}
.secondary-text {
color: var(--secondary-color);
}In this example, --primary-color, --secondary-color, --text-color, and --page-background are custom properties.
The var() function retrieves the value of a custom property and inserts it into a CSS declaration.
The main advantage is centralization. If the primary brand color changes, developers can update its definition instead of searching through the entire stylesheet.
CSS Custom Properties are not limited to colors. They can store dimensions, spacing values, font sizes, border radiuses, shadows, animation durations, layout measurements, and many other valid CSS values.
2. Understanding the Difference Between CSS Variables and Preprocessor Variables
Developers working with Sass or Less may already be familiar with variables. However, CSS Custom Properties and preprocessor variables are not identical.
A Sass variable is evaluated during compilation. Its value is generally replaced with the corresponding value in the generated CSS.
For example, a Sass variable may be written as:
$primary-color: #2563eb;
button {
background-color: $primary-color;
}After compilation, the browser receives ordinary CSS:
button {
background-color: #2563eb;
}The browser does not know that the original stylesheet contained a Sass variable.
CSS Custom Properties work differently.
:root {
--primary-color: #2563eb;
}
button {
background-color: var(--primary-color);
}The browser receives the custom property itself and resolves its value when applying styles.
This difference creates several important capabilities.
CSS Custom Properties can be changed through JavaScript without recompiling stylesheets. Their values can be overridden within specific elements. They participate in inheritance and the cascade. They can also respond to media queries, user preferences, and different theme classes.
Sass variables remain valuable for compile-time calculations, loops, mixins, and stylesheet generation. CSS Custom Properties are particularly valuable when values need to remain configurable in the browser.
Many modern applications use both technologies together.
3. Defining CSS Custom Properties with
One of the most common places to define global CSS variables is the :root selector.
The :root pseudo-class represents the document's root element. In an HTML document, this is normally the html element.
Consider the following example:
:root {
--brand-primary: #2563eb;
--brand-secondary: #0f172a;
--brand-accent: #f59e0b;
--font-family: Arial, sans-serif;
--spacing-small: 8px;
--spacing-medium: 16px;
--spacing-large: 24px;
--border-radius: 8px;
}Because the variables are defined at the root level, descendant elements can generally access them through inheritance.
body {
font-family: var(--font-family);
}
.card {
padding: var(--spacing-medium);
border-radius: var(--border-radius);
}
.primary-button {
background-color: var(--brand-primary);
}Using :root is especially useful when defining shared design tokens for an entire website.
A design token is a reusable design value that represents a decision within a design system. Examples include the primary brand color, standard spacing scale, heading font size, or default border radius.
Instead of treating these values as unrelated CSS declarations, developers can define a consistent vocabulary for the entire application.
4. Using the var() Function
The var() function is used to retrieve custom property values.
Its basic syntax is:
property: var(--custom-property-name);For example:
:root {
--button-background: #2563eb;
}
button {
background: var(--button-background);
}A custom property can be used in multiple declarations.
:root {
--surface-color: #ffffff;
--border-color: #e2e8f0;
--text-color: #0f172a;
}
.card {
background: var(--surface-color);
border: 1px solid var(--border-color);
color: var(--text-color);
}
.panel {
background: var(--surface-color);
border-color: var(--border-color);
}This approach reduces repetition and improves consistency.
However, developers should understand that the var() function does not behave like a universal text-replacement mechanism. The resulting value must still be valid in the property where it is used.
For example, assigning an invalid value to a property can cause that declaration to become invalid at computed-value time.
:root {
--button-size: large;
}
button {
width: var(--button-size);
}The value large is not a valid width value. The browser cannot use it as a valid width declaration.
Custom properties can store almost any token sequence, but the final declaration must satisfy the syntax requirements of the CSS property.
5. Providing Fallback Values
Sometimes a custom property may not be defined in the current element's scope. The var() function supports fallback values for such situations.
The syntax is:
property: var(--custom-property, fallback-value);Example:
button {
background-color: var(--button-color, #2563eb);
}If --button-color is unavailable, the browser uses the fallback color.
Fallback values are particularly useful when building reusable components.
.card {
background-color: var(--card-background, white);
color: var(--card-text-color, #1e293b);
padding: var(--card-padding, 20px);
border-radius: var(--card-radius, 10px);
}A component can work with sensible default values even when the parent application does not provide custom properties.
Fallbacks can also be used for nested variable dependencies.
:root {
--brand-color: #2563eb;
--button-color: var(--brand-color, #1d4ed8);
}One important detail is that fallback values are used when the referenced custom property is missing or has the guaranteed-invalid value. A fallback does not automatically repair every invalid value supplied by an existing custom property.
6. Understanding Inheritance and Scope
CSS Custom Properties follow the normal CSS cascade and inheritance rules by default.
A property defined on a parent element can be inherited by its descendants.
.container {
--text-color: #334155;
}
.container h2 {
color: var(--text-color);
}
.container p {
color: var(--text-color);
}Both the heading and paragraph can access the variable because it is defined on their common parent.
This behavior makes custom properties useful for component-level configuration.
.card {
--card-background: white;
--card-padding: 20px;
background-color: var(--card-background);
padding: var(--card-padding);
}A particular card can override these values without changing other cards.
.card.featured {
--card-background: #eff6ff;
--card-padding: 28px;
}The featured card now receives different values while retaining the same component structure.
This is one of the most powerful aspects of CSS Custom Properties. Developers can create reusable components that accept different styling configurations through inherited values.
7. Creating Component-Level Variables
Global variables are useful for shared design decisions, but not every variable needs to be available throughout the entire website.
Component-level custom properties help keep styling responsibilities organized.
For example:
.pricing-card {
--card-padding: 24px;
--card-border: #e2e8f0;
--card-heading-color: #0f172a;
padding: var(--card-padding);
border: 1px solid var(--card-border);
}
.pricing-card h2 {
color: var(--card-heading-color);
}A premium pricing card can override selected values.
.pricing-card.premium {
--card-border: #2563eb;
--card-heading-color: #1d4ed8;
}This technique separates component structure from individual visual configurations.
It is useful when developing product cards, pricing tables, dashboards, notification components, navigation systems, and reusable UI libraries.
8. Building a Design Token System with CSS Variables
A design token system is a structured collection of reusable values that define the visual language of an application.
Without design tokens, developers may use slightly different values for similar interface elements. One section may use a 15-pixel gap, another may use 16 pixels, and another may use 18 pixels. Over time, these small differences can make a website feel inconsistent.
A token system establishes shared values.
A practical design token structure can be divided into several categories.
Color Tokens
:root {
--color-primary: #2563eb;
--color-primary-dark: #1d4ed8;
--color-secondary: #64748b;
--color-success: #16a34a;
--color-warning: #d97706;
--color-danger: #dc2626;
--color-white: #ffffff;
--color-black: #000000;
}Typography Tokens
:root {
--font-body: Arial, sans-serif;
--font-heading: Georgia, serif;
--font-size-small: 0.875rem;
--font-size-base: 1rem;
--font-size-large: 1.25rem;
--font-size-heading: 2rem;
--font-weight-normal: 400;
--font-weight-medium: 500;
--font-weight-bold: 700;
}Spacing Tokens
:root {
--space-1: 4px;
--space-2: 8px;
--space-3: 12px;
--space-4: 16px;
--space-5: 24px;
--space-6: 32px;
--space-7: 48px;
--space-8: 64px;
}Border and Shadow Tokens
:root {
--radius-small: 4px;
--radius-medium: 8px;
--radius-large: 16px;
--radius-full: 999px;
--shadow-small: 0 2px 6px rgb(15 23 42 / 8%);
--shadow-medium: 0 8px 20px rgb(15 23 42 / 10%);
}Layout Tokens
:root {
--container-width: 1200px;
--header-height: 72px;
--sidebar-width: 260px;
--content-gap: 24px;
}These tokens can be reused throughout the application. If the design system changes, developers can update the relevant tokens centrally.
A well-organized token system should use meaningful names and consistent categories. Names such as --color-primary or --space-4 are generally easier to understand than names such as --blue2 or --gap-new.
9. Creating Dark Mode with CSS Custom Properties
One of the most practical applications of CSS Variables is implementing light and dark themes.
A traditional approach might require developers to write separate color declarations for every component. As an application grows, maintaining these declarations becomes difficult.
CSS Custom Properties allow developers to define a shared set of semantic colors and override them for each theme.
Start with the default light theme.
:root {
color-scheme: light;
--background: #ffffff;
--surface: #f8fafc;
--text: #0f172a;
--muted-text: #64748b;
--border: #e2e8f0;
--primary: #2563eb;
}Next, define dark theme values.
[data-theme="dark"] {
color-scheme: dark;
--background: #0f172a;
--surface: #1e293b;
--text: #f8fafc;
--muted-text: #cbd5e1;
--border: #334155;
--primary: #60a5fa;
}The application components use the semantic properties.
body {
background-color: var(--background);
color: var(--text);
}
.card {
background-color: var(--surface);
border: 1px solid var(--border);
}
.card p {
color: var(--muted-text);
}
button {
background-color: var(--primary);
}When the data-theme attribute changes on the document root, the corresponding variables are recalculated.
This means the same components can support both themes without duplicating their entire stylesheets.
The color-scheme property also informs the browser about the supported color scheme. It can influence the appearance of browser-provided controls, scrollbars, and other native interface elements.
10. Changing Themes with JavaScript
CSS Custom Properties can be updated dynamically through JavaScript.
For example, a theme switcher can change the data-theme attribute on the root element.
<button id="themeToggle">
Switch Theme
</button>const themeToggle = document.querySelector("#themeToggle");
themeToggle.addEventListener("click", () => {
const root = document.documentElement;
const currentTheme = root.dataset.theme;
const nextTheme =
currentTheme === "dark" ? "light" : "dark";
root.dataset.theme = nextTheme;
});The CSS theme definitions handle the visual changes.
Developers can also update individual custom properties directly.
document.documentElement.style.setProperty(
"--primary",
"#7c3aed"
);To read a custom property, use getComputedStyle().
const styles = getComputedStyle(document.documentElement);
const primaryColor = styles
.getPropertyValue("--primary")
.trim();
console.log(primaryColor);This is useful when building configurable dashboards, visual editors, theme customization tools, and applications where users can personalize their interface.
For production applications, theme preferences should be handled carefully. Developers may save a user's selection in local storage or another appropriate preference system, while respecting the user's system-level color preference when no explicit selection exists.
11. Respecting System Dark Mode Preferences
Browsers expose user color-scheme preferences through the prefers-color-scheme media feature.
This allows a website to adapt automatically to the operating system's light or dark mode setting.
:root {
color-scheme: light;
--background: #ffffff;
--text: #0f172a;
--surface: #f8fafc;
}
@media (prefers-color-scheme: dark) {
:root {
color-scheme: dark;
--background: #0f172a;
--text: #f8fafc;
--surface: #1e293b;
}
}The browser applies the dark theme when the user has configured a dark color scheme.
For applications that support both automatic and manually selected themes, the implementation should establish a clear priority. A manual user selection should normally override the automatic system preference.
This creates a more predictable experience and gives users control over how the interface appears.
12. Building Dynamic Layouts with CSS Variables
CSS Variables are not limited to visual colors. They can also control dimensions and layout behavior.
Consider a dashboard with a configurable sidebar.
:root {
--sidebar-width: 260px;
--content-padding: 24px;
}
.dashboard {
display: grid;
grid-template-columns: var(--sidebar-width) minmax(0, 1fr);
min-height: 100vh;
}
.main-content {
padding: var(--content-padding);
}A compact layout can override the sidebar width.
.dashboard.compact {
--sidebar-width: 80px;
}The same layout rules adapt automatically because they reference the custom property.
Variables can also help with responsive spacing.
:root {
--section-padding: 64px;
}
@media (max-width: 768px) {
:root {
--section-padding: 36px;
}
}
@media (max-width: 480px) {
:root {
--section-padding: 24px;
}
}
section {
padding-block: var(--section-padding);
}This approach centralizes responsive values and reduces the need to repeat multiple declarations.
13. Using CSS Variables with clamp() for Fluid Design
The clamp() function allows a CSS value to grow or shrink within defined minimum and maximum limits.
When combined with custom properties, it becomes a useful tool for building fluid design systems.
:root {
--heading-size: clamp(2rem, 5vw, 4rem);
--body-size: clamp(1rem, 1.5vw, 1.125rem);
--section-spacing: clamp(32px, 6vw, 80px);
}
h1 {
font-size: var(--heading-size);
}
body {
font-size: var(--body-size);
}
section {
padding-block: var(--section-spacing);
}This allows typography and spacing to respond smoothly to viewport width without requiring a large number of breakpoints.
However, fluid sizing should be tested carefully. Text must remain readable on small screens, and large headings should not become excessively wide or visually overwhelming.
14. Creating Reusable Components with Configurable Variables
A reusable component should have a predictable structure while allowing controlled customization.
CSS Custom Properties make this possible without creating a separate class for every variation.
Consider a reusable button component.
.button {
--button-background: #2563eb;
--button-text: white;
--button-radius: 8px;
--button-padding: 12px 20px;
background: var(--button-background);
color: var(--button-text);
border: none;
border-radius: var(--button-radius);
padding: var(--button-padding);
cursor: pointer;
}Different variations can override the variables.
.button.success {
--button-background: #16a34a;
}
.button.danger {
--button-background: #dc2626;
}
.button.rounded {
--button-radius: 999px;
}
.button.large {
--button-padding: 16px 28px;
}The HTML remains simple.
<button class="button">
Primary Action
</button>
<button class="button success">
Save Changes
</button>
<button class="button danger rounded">
Delete Account
</button>This pattern can be applied to cards, badges, alerts, navigation components, modal windows, and many other interface elements.
It is especially useful when building component libraries shared across multiple applications.
15. Understanding the @property Rule
CSS also provides the @property rule, which allows developers to register custom properties with additional information.
A registered property can define its syntax, inheritance behavior, and initial value.
For example:
@property --progress {
syntax: "<percentage>";
inherits: false;
initial-value: 0%;
}The property can now be used in an element.
.progress-bar {
width: var(--progress);
height: 10px;
background: #2563eb;
transition: width 400ms ease;
}A particular progress bar can set its own value.
.progress-bar.completed {
--progress: 100%;
}The syntax descriptor defines the type of value accepted by the registered custom property. The inherits descriptor determines whether the property inherits from its parent, and initial-value establishes its default value.
Registration can also make certain custom properties animatable in ways that ordinary unregistered custom properties are not.
For example, a registered numeric property can be transitioned between compatible values.
@property --rotation {
syntax: "<angle>";
inherits: false;
initial-value: 0deg;
}
.rotating-card {
transform: rotate(var(--rotation));
transition: --rotation 500ms ease;
}
.rotating-card:hover {
--rotation: 5deg;
}The @property rule is useful when creating animated design effects, typed configuration values, and more predictable custom-property behavior.
Developers should verify browser support for the specific environments they target and provide appropriate fallbacks when necessary.
16. Using CSS Variables in Animations
Custom properties can make animations easier to configure.
For example:
:root {
--animation-duration: 300ms;
--animation-distance: 12px;
}
.notification {
animation: slideIn var(--animation-duration) ease;
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(var(--animation-distance));
}
to {
opacity: 1;
transform: translateY(0);
}
}The animation duration and movement distance can be adjusted centrally.
A particular component can use different values.
.notification.large {
--animation-duration: 500ms;
--animation-distance: 24px;
}This is helpful when an application has a consistent motion system with shared durations and movement distances.
For accessibility, animations should also respect reduced-motion preferences.
@media (prefers-reduced-motion: reduce) {
.notification {
animation: none;
transition: none;
}
}A motion system should improve usability rather than create unnecessary distractions.
17. Creating Multiple Brand Themes
Applications serving multiple brands or customers may need different visual identities.
Instead of creating separate stylesheets for every brand, developers can define theme-specific custom properties.
:root {
--brand-primary: #2563eb;
--brand-secondary: #0f172a;
--brand-accent: #f59e0b;
}
[data-brand="green"] {
--brand-primary: #15803d;
--brand-secondary: #14532d;
--brand-accent: #facc15;
}
[data-brand="purple"] {
--brand-primary: #7c3aed;
--brand-secondary: #3b0764;
--brand-accent: #c4b5fd;
}Components can use the same variables regardless of the selected brand.
.brand-button {
background-color: var(--brand-primary);
color: white;
}
.brand-heading {
color: var(--brand-secondary);
}
.brand-highlight {
color: var(--brand-accent);
}The selected brand can be changed through JavaScript.
document.documentElement.dataset.brand = "green";This pattern is particularly useful for SaaS platforms, white-label products, multi-tenant applications, and websites that offer customer-specific branding.
18. Organizing CSS Variables in Large Projects
As a project grows, placing every custom property in a single unstructured block can become difficult to maintain.
A more effective approach is to organize tokens by responsibility.
For example:
:root {
/* Colors */
--color-primary: #2563eb;
--color-secondary: #64748b;
--color-background: #ffffff;
--color-surface: #f8fafc;
/* Typography */
--font-body: Arial, sans-serif;
--font-heading: Georgia, serif;
--font-size-base: 1rem;
/* Spacing */
--space-small: 8px;
--space-medium: 16px;
--space-large: 24px;
/* Borders */
--radius-medium: 8px;
--border-default: 1px solid #e2e8f0;
/* Layout */
--container-max-width: 1200px;
}A larger project may separate these responsibilities into different CSS files.
For example:
styles/
tokens.css
themes.css
typography.css
layout.css
components.css
utilities.css
main.cssThe token file contains shared design values, while the theme file defines theme-specific overrides.
The component stylesheet references the tokens rather than repeating hardcoded values.
This structure improves collaboration because developers can locate and modify design decisions more easily.
19. CSS Variables in React Applications
CSS Custom Properties work naturally with React because they are browser-native CSS features.
A React component can define styles using custom properties.
function ProfileCard() {
return (
<article className="profile-card">
<h2>Developer Profile</h2>
<p>Frontend and backend development</p>
</article>
);
}.profile-card {
--card-color: #2563eb;
border: 1px solid var(--card-color);
padding: 20px;
border-radius: 12px;
}React can also pass custom properties dynamically through inline styles.
function ThemeCard({ color }) {
return (
<div
className="theme-card"
style={{ "--card-color": color }}
>
Custom Theme Card
</div>
);
}.theme-card {
background-color: var(--card-color);
color: white;
padding: 24px;
border-radius: 12px;
}In TypeScript projects, developers may need an appropriate style type or a small type extension depending on the project's React and TypeScript definitions.
CSS Variables are useful in React applications because they allow dynamic values to be passed into styling without requiring a separate CSS class for every possible value.
20. CSS Variables in Next.js Applications
Next.js supports ordinary CSS features, including CSS Custom Properties.
A project can define global design tokens in a global stylesheet.
:root {
--primary: #2563eb;
--background: #ffffff;
--text: #0f172a;
}
[data-theme="dark"] {
--primary: #60a5fa;
--background: #0f172a;
--text: #f8fafc;
}Components can then reference these properties.
.page {
background: var(--background);
color: var(--text);
}
.action-button {
background: var(--primary);
}CSS Modules can also use global custom properties.
.card {
background: var(--surface, #ffffff);
color: var(--text, #0f172a);
border-radius: var(--radius-medium, 8px);
}This makes it possible to combine locally scoped component styles with globally shared design tokens.
When implementing themes in server-rendered applications, developers should consider how the initial theme is selected. Applying the correct theme before the page visibly renders can help avoid a flash of the wrong theme.
21. CSS Variables for Accessible Design Systems
Custom Properties can help developers implement accessible design systems by centralizing values related to readability, contrast, focus indicators, and interaction states.
For example:
:root {
--text-primary: #172554;
--background-primary: #ffffff;
--focus-color: #2563eb;
--focus-width: 3px;
}
button:focus-visible,
a:focus-visible,
input:focus-visible {
outline: var(--focus-width) solid var(--focus-color);
outline-offset: 3px;
}A shared focus token helps maintain consistent keyboard navigation indicators.
However, using variables does not automatically make a design accessible. Developers must still evaluate color contrast, font readability, keyboard interactions, form labels, focus visibility, and semantic HTML.
Theme changes should also be tested with assistive technologies and different display settings.
A dark theme, for example, should not simply invert every color. It should use carefully selected foreground and background combinations that remain readable and visually comfortable.
22. Common Mistakes When Using CSS Variables
Although CSS Custom Properties are straightforward, some implementation mistakes can make a stylesheet difficult to maintain.
Using Unclear Variable Names
Names such as --blue-one, --blue-two, or --value-new do not communicate the purpose of a value.
Prefer names that explain the role of the property.
For example, --color-primary, --text-muted, and --surface-background are easier to understand.
Defining Every Variable Globally
Not every component value needs to be available throughout the entire document.
Defining component-specific values near the component can make the stylesheet easier to understand and reduce accidental dependencies.
Repeating Hardcoded Values
A stylesheet that defines custom properties but continues to repeat the same hardcoded values defeats part of the purpose.
Shared design decisions should reference the relevant tokens.
Creating Excessively Complex Dependencies
A custom property can reference another custom property, but long chains of dependencies can become difficult to debug.
Keep token relationships understandable and avoid unnecessary layers.
Forgetting Fallback Values
Reusable components may be used in contexts where a parent does not define the expected variable.
Sensible fallbacks can make components more robust.
Ignoring Inheritance
A custom property defined on a parent can affect many descendants.
Developers should understand where variables are defined and which components inherit them.
Treating Custom Properties Like Sass Variables
CSS Custom Properties remain available in the browser and follow runtime CSS behavior. They are not simply compile-time placeholders.
Understanding this distinction helps developers choose the right tool for the job.
Failing to Test Theme Combinations
A color combination that looks good in a light theme may become difficult to read in a dark theme.
Every theme should be tested across buttons, links, cards, forms, alerts, tables, and interactive states.
23. Best Practices for Professional CSS Variable Architecture
A professional implementation should treat CSS Variables as part of the design system rather than merely a way to avoid repeating colors.
Start by defining a small set of foundational tokens for colors, typography, spacing, borders, and layout.
Use semantic names that explain the purpose of a value. For example, --text-primary communicates more than a variable named --gray-900 when used inside a component.
Separate primitive values from semantic values when the project is large enough to benefit from that distinction. A primitive token may represent a color such as blue 600, while a semantic token may represent the primary action color that currently uses blue 600.
Keep component-level variables close to their components. This makes it easier to understand which values are configurable and which are internal implementation details.
Use consistent naming conventions across the project. A predictable structure reduces confusion during code reviews and team collaboration.
Avoid creating variables for every isolated declaration. Variables are most valuable when they represent reusable decisions, configurable values, or important relationships within the design system.
Test custom properties across different themes, responsive breakpoints, browser environments, and component states.
Finally, document important design tokens. A shared design system should help designers and developers understand not only what a value is, but why it exists and where it should be used.
24. Practical Project: Build a Themeable Business Dashboard
A useful way to understand CSS Variables is to build a small dashboard that supports light and dark themes.
The dashboard will include a header, sidebar, main content area, statistic cards, and action buttons.
Step 1: Define the HTML Structure
<div class="dashboard">
<header class="header">
<h1>Business Dashboard</h1>
<button id="themeToggle">Toggle Theme</button>
</header>
<div class="dashboard-layout">
<aside class="sidebar">
<nav>
<a href="#">Overview</a>
<a href="#">Reports</a>
<a href="#">Customers</a>
<a href="#">Settings</a>
</nav>
</aside>
<main class="main-content">
<h2>Overview</h2>
<div class="cards">
<article class="card">
<h3>Total Revenue</h3>
<p>₹2,45,000</p>
</article>
<article class="card">
<h3>Customers</h3>
<p>1,240</p>
</article>
<article class="card">
<h3>Orders</h3>
<p>860</p>
</article>
</div>
</main>
</div>
</div>Step 2: Define Theme Variables
:root {
color-scheme: light;
--background: #f8fafc;
--surface: #ffffff;
--text: #0f172a;
--muted: #64748b;
--border: #e2e8f0;
--primary: #2563eb;
}
[data-theme="dark"] {
color-scheme: dark;
--background: #0f172a;
--surface: #1e293b;
--text: #f8fafc;
--muted: #cbd5e1;
--border: #334155;
--primary: #60a5fa;
}Step 3: Style the Dashboard
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: Arial, sans-serif;
background: var(--background);
color: var(--text);
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px 28px;
background: var(--surface);
border-bottom: 1px solid var(--border);
}
.dashboard-layout {
display: grid;
grid-template-columns: 240px minmax(0, 1fr);
min-height: calc(100vh - 80px);
}
.sidebar {
padding: 24px;
background: var(--surface);
border-right: 1px solid var(--border);
}
.sidebar nav {
display: grid;
gap: 16px;
}
.sidebar a {
color: var(--muted);
text-decoration: none;
}
.main-content {
padding: 28px;
}
.cards {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 20px;
}
.card {
padding: 24px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 12px;
}
.card h3 {
color: var(--muted);
}
.card p {
font-size: 1.5rem;
font-weight: 700;
}
button {
background: var(--primary);
color: white;
border: none;
padding: 10px 16px;
border-radius: 8px;
cursor: pointer;
}Step 4: Add Responsive Layout Rules
@media (max-width: 768px) {
.dashboard-layout {
grid-template-columns: 1fr;
}
.sidebar {
border-right: none;
border-bottom: 1px solid var(--border);
}
.cards {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 480px) {
.header {
align-items: flex-start;
gap: 12px;
flex-direction: column;
}
.cards {
grid-template-columns: 1fr;
}
.main-content {
padding: 18px;
}
}Step 5: Add the Theme Switcher
const themeToggle = document.querySelector("#themeToggle");
const root = document.documentElement;
themeToggle.addEventListener("click", () => {
const currentTheme = root.dataset.theme || "light";
const newTheme =
currentTheme === "light" ? "dark" : "light";
root.dataset.theme = newTheme;
});This project demonstrates how CSS Custom Properties can control an entire interface without requiring duplicate component stylesheets.
The same approach can be extended to include persistent theme preferences, multiple brand palettes, user-configurable accent colors, and additional dashboard layouts.
25. The Future of CSS Custom Properties
CSS continues to evolve, and Custom Properties are an important part of modern styling architecture.
Developers increasingly use them to build reusable design systems, configurable component libraries, multi-brand applications, and themeable interfaces.
Features such as registered custom properties through @property provide additional control over types, inheritance, and animation behavior.
CSS nesting, container queries, modern color functions, and other evolving CSS capabilities also complement custom properties. Together, these features allow developers to create increasingly sophisticated interfaces while keeping much of the styling logic inside native CSS.
CSS Variables are also useful in design-to-code workflows. Design tokens can be translated into CSS custom properties, allowing visual design decisions to be shared more consistently between design tools and frontend implementations.
As applications become more modular, the ability to configure components through inherited custom properties will remain valuable.
Conclusion
CSS Variables and Custom Properties are essential tools for building modern, maintainable, and scalable websites. They allow developers to define reusable values, centralize design decisions, configure components, create responsive layouts, implement dark mode, and support multiple visual themes.
Their greatest advantage is that they operate directly in the browser. Unlike traditional preprocessor variables, CSS Custom Properties participate in the cascade, support inheritance, and can be updated dynamically through JavaScript.
For small projects, they make stylesheets easier to maintain. For larger applications, they provide a foundation for design tokens, reusable component systems, and consistent visual architecture.
Developers should learn to use global tokens for shared design decisions, local custom properties for component configuration, semantic naming for clarity, and fallbacks for reusable components. They should also understand inheritance, runtime updates, theme precedence, and accessibility considerations.
Whether you are developing a personal website, a business application, an e-commerce platform, or a large SaaS dashboard, CSS Custom Properties can help you write cleaner stylesheets and build interfaces that are easier to customize and maintain.
The next step is to practice by converting repeated colors, spacing values, typography settings, and component styles into a structured design token system.
#CSSVariables #CSSCustomProperties #WebDevelopment #FrontendDevelopment #DesignSystems