var()

CSS variables, also known as custom properties, are a powerful feature that allows you to store values that can be reused throughout your stylesheets. This makes your CSS more organized, maintainable, and easier to theme.

How to use var() ?

  • Defining a variable: You define a variable using a double-hyphen prefix (–) followed by the variable name. This is typically done at the :root selector to set a global variable.
:root {
  --primary-color: #333;
  --font-family: Arial, sans-serif;
}
  • Using a variable: To use a variable, use the var() function. Inside the parentheses, provide the name of the variable you want to use.
body {
  color: var(--primary-color);
  font-family: var(--font-family);
}

Why use var()?

  • Reusability: Once a variable is defined, it can be used multiple times throughout your stylesheet.
  • Maintainability: If you need to change a color or font, you only need to update it in one place, and all elements using that variable will automatically update.
  • Theming: CSS variables make it easy to create different themes for your website. By changing the values of a few variables, you can completely alter the look and feel of your site.
  • Dynamic values: You can even use JavaScript to change the values of CSS variables, allowing for dynamic styling based on user interactions or other factors.

Example: Creating a simple theme

:root {
  --primary-color: #333;
  --secondary-color: #f0f0f0;
  --font-family: Arial, sans-serif;
}

body {
  background-color: var(--secondary-color);
  color: var(--primary-color);
  font-family: var(--font-family);
}

.button {
  background-color: var(--primary-color);
  color: var(--secondary-color);
}

To create a dark theme, you could simply change the values of --primary-color and --secondary-color at the :root level.

Additional notes

  • Scoped variables: You can define variables at any level of your CSS, not just at the :root level. Variables defined within a selector will only be accessible to that selector and its descendants.
  • Fallback values: If a variable is not defined or if its value is invalid, you can provide a fallback value within the var() function. For example: color: var(--primary-color, blue);
  • Browser compatibility: CSS variables are well-supported in modern browsers. For older browsers, you can use a CSS preprocessor like Sass or Less to create fallbacks.