CSS Variables

❮ Previous Home Next ❯

The CSS variables allow a value to be stored in one place, then referenced in multiple other places.

The CSS Variables make it possible to change CSS dynamically at runtime.

The CSS variables make it easier than ever to override components to match a theme(s).




Declaration

By using a custom property name that begins with a double hyphen (--), and a property value that can be any valid CSS value.

Syntax:

element {
  --customPropertyName: red;
}

A common best practice is to define custom properties on the :root pseudo-class, so that it can be applied globally across your HTML document.

Note: Custom property names are case sensitive like --color will be treated as a separate custom property to --Color.




Global Variables

The CSS variables can be set globally by using the :root selector.

Hello World!

Example

:root {
  --color: red;
  --bg-color: yellow;
}

p {
  color: var(--color);
  background-color: var(--bg-color);
}



Local Variables

The CSS variables can be set local also.

Example 1:

Hello World!

Example

:root {
  --color: red;
  --bg-color: yellow;
}

p {
  --size: 32px;
  color: var(--color);
  background-color: var(--bg-color);
  font-size: var(--size)
}

Example 2:

Hello World!

Example

.example {
  --color: red;
  --bg-color: yellow;
}

p {
  --size: 32px;
  color: var(--color);
  background-color: var(--bg-color);
  font-size: var(--size)
}

Example 1:

Hello World!

Example

<style>
p {
  --color: red;
  --bg-color: yellow;
}

.example {
  --size: 32px;
  color: var(--color);
  background-color: var(--bg-color);
  font-size: var(--size)
}
</style>

<p class="example">Hello World!</p>






The CSS Variables Fallback Values

You can define multiple fallback values when the given variable is not yet defined; this can be useful when working with Custom Elements and Shadow DOM.

If the browser doesn't support CSS custom properties, the fallback value won't help.

Hello World!

Example

:root {
  --color: red;
  --bg-color: yellow;
}

p {
  background-color: var(--bg-clor, red);
}



The CSS Variables in Media Queries

The following is a simple example to demonstrate how you can use variable function in media queries:

Example

:root {
  --color: white;
  --bg-color: black; 
}

body {
  background-color: var(--bg-color);
}

h1, h2, p {
  color: var(--color)
}

@media screen and (min-width: 500px) {
:root {
  --color: black;
  --bg-color: white; 
}
}



CSS var() Function

Functions Description
var() Specifies the value of a custom property (CSS variable) instead of any part of a value of another property.
❮ Previous Home Next ❯