CSS Variables and Modern Functions
Modern CSS is no longer just a static list of properties. With variables and functions, we can create themes, spacing systems, dynamic colors, and responsive layouts without repeating code.
1. CSS Variables (--name)
CSS variables allow the definition of reusable values that are easy to modify. They are defined inside a
selector (usually :root) and accessed using var().
:root {
--primary-color: #3498db;
--spacing: 16px;
}
.button {
background: var(--primary-color);
padding: var(--spacing);
}
2. Modern Functions: calc(), clamp(), min(), max()
These functions allow calculations directly in CSS, useful for responsive and scalable layouts.
calc()– combines units:width: calc(100% - 20px)clamp()– defines a value between a minimum and a maximum:font-size: clamp(1rem, 2vw, 2rem)min()/max()– choose the smallest / largest value
3. Theming and Easy Maintenance
With variables, you can change a site's theme from a single location. You can even override them based on media queries or modes (dark/light).
:root {
--bg-color: #ffffff;
--text-color: #000000;
}
@media (prefers-color-scheme: dark) {
:root {
--bg-color: #121212;
--text-color: #f5f5f5;
}
}
body {
background: var(--bg-color);
color: var(--text-color);
}
Example – Theme Toggle with CSS Variables
This example uses CSS variables to define theme colors and a button that toggles between light and dark mode.
Everything is controlled via a class on the <body>.
Best Practices
Define variables in :root
This way they become globally accessible throughout the document.
:root {
--primary-color: #3498db;
--font-size-base: 1rem;
}
Use clamp() for scalability
Ideal for responsive fonts and spacing.
font-size: clamp(1rem, 2vw, 1.5rem);
Use calc() for flexible layout
Combines units for dynamic sizing.
width: calc(100% - 40px);
Use min() and max() for predictive control
Limits dimensions based on the viewport.
width: min(100%, 600px);
Group variables by category
Organize them for easier maintenance.
:root {
/* Colors */
--color-bg: #fff;
--color-text: #333;
/* Spacing */
--space-sm: 8px;
--space-md: 16px;
/* Fonts */
--font-base: 1rem;
}
Use fallback in var()
Make sure you have a fallback value.
color: var(--text-color, #000);
Theme using classes or media queries
Switch the theme with a global class or detect it automatically.
:root.dark {
--color-bg: #121212;
--color-text: #f5f5f5;
}
Document your variables
Add clear comments for each group.
:root {
/* Main theme colors */
--primary: #3498db;
}
When CSS variables are well-structured and modern functions are used wisely, styles become not only elegant but also scalable, easy to maintain, and ready for any design challenge.
