Dynamic CSS with Variables (Custom Properties): Creating Reusable and Maintainable Styles

Learn how to use CSS variables (custom properties) to create reusable styles and improve maintainability in your CSS. This tutorial explains variable declaration, scope, the `var()` function, and best practices for using CSS variables to create efficient and easily updatable stylesheets.



Using CSS Variables (Custom Properties)

What are CSS Variables?

CSS variables (also called custom properties) let you define reusable values that you can use throughout your stylesheets. They're declared using a custom property notation (e.g., `--my-variable: blue;`) and accessed using the `var()` function. This makes your CSS more organized, easier to maintain, and simpler to update.

Declaring CSS Variables

Variables are defined using double dashes (`--`) followed by the variable name. The variable name is case-sensitive (`--myVar` and `--myvar` are different).

The scope of a variable depends on where it's declared:

  • Within a specific selector: The variable is only available within that selector and its descendants.
  • On the :root pseudo-class: The variable is globally available throughout your entire document.
Example: Declaring a Variable

:root {
  --main-color: #007bff; /* Global variable */
}

.my-element {
  --text-color: #333; /* Variable only available within .my-element */
}

The `var()` Function

The `var()` function retrieves the value of a custom property.

`var()` Syntax

var( --custom-property-name, )

  • --custom-property-name: The name of your CSS variable (required; must start with two dashes).
  • : (Optional) A fallback value to use if the custom property is not defined or has an invalid value. This is not for browser compatibility; browsers that don't support CSS variables will ignore the `var()` function entirely.

Examples of CSS Variables and Fallback Values

These examples illustrate how to use CSS variables and fallback values. You'd need corresponding HTML to see this in a browser.

Example CSS

:root {
  --main-color: green;
}

p {
  color: var(--main-color, blue); /* Uses green; if --main-color is undefined it uses blue */
}

This example shows how the fallback value (`blue`) is only used if the variable `--main-color` is not defined.

Using `calc()` with `var()`

You can use the `calc()` function to perform calculations with variable values.

Example CSS

:root {
  --base-size: 10px;
}

.my-element {
  padding: calc(2 * var(--base-size));
  font-size: calc(1.5 * var(--base-size));
}