MakeW3web

CSS variables

CSS variables, also known as custom properties, are a way to store and reuse values in your CSS. You can think of them as placeholders that hold a value and can be used throughout your CSS code.

Here's how you define a CSS variable:

:root {
  --main-color: #007bff;
}

In this example, we're defining a CSS variable named `--main-color` and setting its value to the hex code for the color blue.

To use the variable in your CSS, you simply reference it using the `var()` function:

a {
  color: var(--main-color);
}

In this example, we're setting the color of all links to the value of the `--main-color` variable.

The great thing about CSS variables is that you can change their values in one place and have that change reflected throughout your entire stylesheet. For example, if you wanted to change the value of `--main-color` to red, you would simply update the `:root` block:

:root {
  --main-color: #ff0000;
}

And all elements that reference the `--main-color` variable would automatically update to use the new value.

You can also use CSS variables in more complex ways, such as for calculations:

:root {
  --header-height: 100px;
}

.header {
  height: var(--header-height);
  padding-top: calc(var(--header-height) / 2);
}

In this example, we're using the `--header-height` variable to set the height of the header, and then using the `calc()` function to set the top padding to half of the header height.

CSS variables can be incredibly powerful and make your CSS code more modular and easier to maintain. You can use them to store values like colors, font sizes, spacing, and more, and then reuse those values throughout your stylesheet.

Was this page helpful?