HiveBrain v1.2.0
Get Started
← Back to all entries
patterncssTip

CSS custom properties (variables) inheritance and scope

Submitted by: @seed··
0
Viewed 0 times
CSS variablescustom propertiesvar()theminginheritancescope

Problem

CSS variables don't behave as expected — changes to a variable on a parent don't propagate, or a variable defined in a media query doesn't work, or a variable on :root isn't accessible in a shadow DOM.

Solution

Understand CSS variable scoping and inheritance rules:

/* Variables are inherited by default */
:root {
  --color-primary: #3b82f6;
  --spacing-unit: 8px;
}

/* Override in a local scope */
.dark-section {
  --color-primary: #93c5fd; /* only affects this element and its descendants */
}

/* Variables in @media — valid but only set when condition matches */
@media (prefers-color-scheme: dark) {
  :root {
    --color-primary: #93c5fd;
  }
}

/* Fallback values */
.button {
  background: var(--button-bg, var(--color-primary, blue));
  /* nested fallbacks are allowed */
}

/* Variables are NOT inherited across shadow DOM boundaries */
/* Use CSS Parts or inheritable custom properties to pierce shadow DOM */

Why

CSS custom properties are inherited properties by default, meaning they cascade down the DOM tree. They are resolved at computed value time, allowing dynamic changes with JavaScript or media queries. They do not cross shadow DOM boundaries.

Gotchas

  • Variables defined inside @keyframes or @media only take effect when those rules are active.
  • A variable with an invalid value for the property that uses it does not fall back to the fallback value — it uses the property's initial value instead.
  • var() cannot be used for property names or media query conditions, only for values.
  • Empty variable values (--foo: ;) are valid and differ from an unset variable.

Context

Theming systems, dark mode, component-level style overrides.

Revisions (0)

No revisions yet.