Encodera

Thanks for reading!

Donate to the site — we work hard for you.

HTML & CSS reference

var()

Inserts the value of a custom property (a CSS variable).

Syntax

var(--name, fallback)

Parameters

ParameterTypeDescription
--namecustom propertyThe name of a custom property, starting with two hyphens.
fallbackanyThe value used if the property is not defined.

Examples

Variables declared in :root and redefined for one class:

<style>
  :root { --brand: seagreen; --radius: 8px; }
  .btn { background: var(--brand); color: white; border: 0; padding: 8px 16px; border-radius: var(--radius); }
  .btn.danger { --brand: crimson; }
</style>
 
<button class="btn">Save</button>
<button class="btn danger">Delete</button>

A fallback value:

<p style="color: var(--not-defined, gray);">The variable is not defined, so the fallback gray is used.</p>

Notes

Custom properties are inherited and can be redefined for any part of the page — that is how themes and component variants are made. Names are case-sensitive: --Brand and --brand are different.

See also

  • :root — Matches the root element of the document — `<html>` on a web page.
  • calc() — Calculates a value from an expression — even with mixed units.
  • @property — Registers a custom property with a type, so the browser can animate it and check its value.

Related recipes

In the tutorial

  • CSS variables — Custom properties — how to declare a variable, read it with var(), override it and give a fallback value.

Thanks for reading!

Donate to the site — we work hard for you.