CSS Variables

Introduction to CSS Variables

A cat looking at a computer screen

CSS variables, also known as Custom Properties, allow you to store values that can be reused throughout your CSS.

They are defined with a name that starts with two dashes ( e.g., --my-variable ) and can be accessed using the var() function as the value of any CSS property.

body {
  --heading-color: rebeccapurple;
  --paragraph-color: darkcyan;
}

h1 {
  color: var(--heading-color);
}

p {
  color: var(--paragraph-color);
}

Variable values can be a string, keyword, number, color, unit, css function, or even another css variable. Basically any value that a standard css property would accept, or even just part of it.

:root {
  // String.
  --content-grid-areas: 'sidebar content';

  // Keyword.
  --callout-justify-content: space-between;

  // Number.
  --card-index: 3;

  // Color.
  --card-color-primary: hsl(141.6 72.4% 45.2%);

  // Unit.
  --card-border-radius: 0.25rem;

  // CSS Function.
  --icon-size: calc(1.5rem + 1vw);

  // CSS Variable.
  --card-color-primary: var(--color-blue-300);
}

CSS Variables are most useful when you need to store a value that is going to be reused throughout your CSS.

This becomes incredibly powerful when theming or using calculations to generate values.

They are also self-referencing, which simplifies the debugging process and prevents magic numbers from being used.

body {
  background: hsl(227.1 29.5% 16.7%);
}

.card {
  background: hsl(0 100% 100%);
  border: solid hsl(0 0% 0%);
  border-width: 12px 4px 4px;
  border-radius: 0.25rem;

  &:where(.card--hope) {
    border-color: hsl(141.6 72.4% 45.2%);

    h2 {
      color: hsl(141.6 72.4% 45.2%);
    }

    button {
      border-color: hsl(141.6 72.4% 45.2%);
    }
  }

  &:where(.card--empire) {
    border-color: hsl(219.6 100% 50.2%);

    h2 {
      color: hsl(219.6 100% 50.2%);
    }

    button {
      border-color: hsl(219.6 100% 50.2%);
    }
  }

  &:where(.card--jedi) {
    border-color: hsl(0.7 89.6% 57.2%);

    h2 {
      color: hsl(0.7 89.6% 57.2%);
    }

    button {
      border-color: hsl(0.7 89.6% 57.2%);
    }
  }

  button {
    border-radius: 0.25rem;
  }
}