HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

CSS Variables

CSS Variables (formally known as custom properties) allow you to store specific values that you can reuse throughout your entire document. This makes your CSS much easier to maintain, especially for colors, fonts, and spacing.


The :root Selector

Variables are usually declared in the :root selector so they are available globally throughout the document. Variables must start with two dashes (--).

:root {
  --main-color: #2e7d52;
  --main-bg: #f4f4f4;
  --padding-md: 15px;
}

Using the var() Function

To use a variable, you wrap its name in the var() function.

I am styled with CSS Variables!
.box {
    color: var(--main-color);
    padding: var(--padding-md);
    background-color: var(--main-bg);
}

Why Use Variables?

  • Global Updates: To change a primary color site-wide, you only need to update the variable in :root.
  • Readability: var(--brand-blue) is more readable than #00aaff.
  • Theming: CSS Variables make it very easy to implement "Dark Mode" by simply swapping the variable values.

Tip: You can provide a fallback value inside the var function in case the variable is not defined: var(--my-color, black).