Combining Custom Properties with calc()
- CSS Basics
- Selectors & Specificity
- Box Model & Units
- Typography & Text Styling
- Colors & Color Spaces
- Positioning & Stacking Context
- Flexbox
- Grid
- Grid Advanced
- Responsive Design
- Container Queries
- Pseudo-classes & Pseudo-elements
- Modern Selectors
- CSS Custom Properties
- CSS Functions
- Transitions & Animations
- Transforms
- Forms & Input Styling
- CSS Architecture & Methodologies
- Accessibility in CSS
- Performance & Optimization
- View Transitions & Modern APIs
- Cascade Layers & Scope
Why Custom Properties and calc() Work Well Together
Custom properties store a reusable value; calc() performs math on values, including custom properties. Combined, they let a whole scale of related sizes be derived from a single base variable.
A Basic Combination
:root {
--spacing-unit: 8px;
}
.card {
padding: calc(var(--spacing-unit) * 2); /* 16px */
margin-bottom: calc(var(--spacing-unit) * 3); /* 24px */
}Changing --spacing-unit in one place automatically updates every calculation that depends on it throughout the stylesheet.
Building a Simple Type Scale
:root {
--base-size: 1rem;
--scale: 1.25;
}
h3 { font-size: calc(var(--base-size) * var(--scale)); }
h2 { font-size: calc(var(--base-size) * var(--scale) * var(--scale)); }
h1 { font-size: calc(var(--base-size) * var(--scale) * var(--scale) * var(--scale)); }Adjusting --scale once changes the relationship between every heading level consistently, rather than editing several unrelated font-size values by hand.
Mixing Units Inside calc()
.sidebar {
width: calc(100% - var(--spacing-unit) * 4);
}calc() can freely mix different units - here percentages and pixels - something that is not possible with a plain arithmetic expression outside of calc().
The Practical Payoff
This pairing is the foundation of most modern design-system approaches: define a small number of base variables (spacing unit, base font size, scale ratio), then derive every other size from them with calc(), keeping the whole system consistent and easy to adjust from one place.