CSS Variables & Functions

Article Summary

Learn how to use CSS variables (--name) and functions like calc(), min(), and clamp() to write flexible, maintainable styles with ease.

Modern CSS gives us powerful tools like variables and math functions to create dynamic, scalable, and easier-to-maintain styles—just like in real programming.

🔹 CSS Variables (Custom Properties)

CSS variables let you store values and reuse them anywhere in your styles.

✅ Declaring & Using Variables

:root {
  --primary-color: #007bff;
  --padding-base: 1rem;
}

.button {
  background-color: var(--primary-color);
  padding: var(--padding-base);
}
  • Use :root to define global variables.
  • Access using var(--variable-name)

✅ Scope Example

.card {
  --shadow-color: rgba(0, 0, 0, 0.2);
  box-shadow: 0 4px 6px var(--shadow-color);
}

🎯 Variables can be scoped to specific elements!

🔹 calc() Function

calc() lets you perform math inside CSS, mixing units or adjusting spacing.

✅ Examples:

.container {
  width: calc(100% - 60px);
}

.card {
  padding: calc(1rem + 10px);
}

You can use:

  • +, -, *, / (with proper spacing)
  • Combine %, px, rem, etc.

🔹 min() and max()

  • min(A, B): Picks the smaller of the two.
  • max(A, B): Picks the larger.

✅ Example:

.section {
  width: min(90vw, 1200px); /* Responsive max width */
}
.card {
  padding: max(1rem, 20px);
}

🔹 clamp() – Responsive Sizing Made Easy

Clamp lets you set a fluid value with boundaries.

font-size: clamp(1rem, 2.5vw, 2rem);
  • Min: 1rem
  • Preferred: 2.5vw
  • Max: 2rem

🎯 Clamp is perfect for typography, padding, margins, etc.

🧠 Combine Them!

:root {
  --gap: 2rem;
}

.grid {
  display: grid;
  gap: clamp(1rem, 2vw, var(--gap));
}

This makes layout spacing fluid, scalable, and readable.

✅ Summary Covered

  • --variables and var() usage and scope
  • calc() for inline calculations
  • min(), max() for conditional sizing
  • clamp() for fluid responsiveness
  • Practical use cases and combos
Was this helpful?