OneBite.Dev - Coding blog in a bite size

use css variables

Code snippet for how to use css variables with sample and detail explanation

Using CSS Variables: A Simple Guide

CSS variables, also known as CSS custom properties, are fluent in making your code cleaner, easier to manage, more flexible, and potentially smaller in size. This article will walk you through the simple usage of CSS variables in your stylesheets.

Code Snippet for CSS Variables

To define a CSS variable, we must first assign a value to a property that starts with --, such as --main-color. Below is a simple example of how to utilise CSS variables:

:root {
  --main-color: #c06;
  --secondary-color: #036;
}

body {
  background-color: var(--main-color);
  color: var(--secondary-color);
}

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

Code Explanation for CSS Variables

In this code snippet, we are first defining two variables --main-color and --secondary-color inside the :root selector. The :root pseudo-class is a global selector which allows these variables to be accessed in any part of your CSS code. It’s similar to the html selector, but has a higher specificity.

The --main-color is assigned the value #c06 and --secondary-color is assigned the value #036. These values are arbitrary and you can certainly assign any value according to your need.

Next, in the body rule set, we are using the vars --main-color and --secondary-color as the values for background-color and color respectively, using the var() function. You can see the advantage here: if you later decide to change the colors, you don’t have to sift through all your style sheets looking to change every occurrence. Instead, you simply change the value of the variable.

Lastly, we are demonstrating that these variables can be used in other rule sets. In the button rule set, we’ve reversed the use of --main-color and --secondary-color, showing flexibility of CSS variables to streamline your stylesheet.

In conclusion, CSS variables provide an efficient way to manage and apply repeated values in your stylesheets. By adopting CSS variables, you can maintain cleaner code that is easier to read and modify.

css