Search code examples
css-variables

CSS custom properties as fallback value of another one instead of fixed (predefined) value


CSS Custom Properties allows fallback values in case of missing variable so, for example:

:root {
  --color1:red;
  --color2:blue;
}

body {
  background:var(--color1,gray);
  color:var(--foo,yellow);
}

will result in a BODY with red background color (because --color1 does exist), but with yellow color for text because --foo custom properties does not exist.

It seems not possible to use a CSS custom properties also for the fallback value, so this code:

body {
  background:var(--color1,gray);
  color:var(--foo,--color2);
}

will not result in a blue text, but it will be used default browser color, tipically black one.

Why this behaviour?


Solution

  • Custom properties or CSS variables are only accessed using the var() function.

    Use var(--my-var, var(--my-background, pink)).

    For more information, checkout out Custom property fallback values.