CSS Variable

By Xah Lee. Date: . Last updated: .

CSS allows you you use variable. This is called CSS custom property.

Declare variable like a property, but with the property name with prefix of 2 hyphens, like this:

--xx: red

Then, use it like this:

color: var(--xx)

Here's example.

<div class="xyz">something</div>
:root {
 --xx: pink;
 --yy: 2rem;
 --zz: solid thin red;

color: var(--xx);
font-size: var(--yy);
border: var(--zz);

The :root means root of the HTML or XML. You can also use html, but :root is better because in XML (example: SVG), the root is not html.

There must be no space after var.

Technically, CSS variable is called a CSS custom property. You should think of it as custom property, because, it is used just like properties, with the same cascading precedence for their scope, and overwriting a value is also the same as CSS cascade.

Browser Support

CSS custom property is supported by all major browsers since 2017 Jan, except Internet Explorer.

CSS Misc

  1. Computed Style
  2. Pseudo Class vs Pseudo Element
  3. Media Query
  4. Variable
  5. calc
  6. Reset
  7. user-select
  8. Data URI Scheme
  9. protocol-relative URL
  10. Default Unit
  11. Declaring Character Set in CSS File
  12. Jargons Explained: Tag, Element, Node, Object, Attribute, Property, Method
Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Object Ref
  5. DOM Scripting
  6. SVG
  7. Blog