Sub topic 7
Theming across component boundaries with CSS custom properties
This chapter assumes you can write a standalone Angular component with the @Component decorator and that you know basic CSS selectors, specificity and inheritance. You should also know what Emulated view encapsulation does, which an earlier chapter covered. Here you will use CSS custom properties to let a parent, a page or a global stylesheet theme a component without breaking its encapsulation.
The problem: encapsulation blocks outside rules
Under the default Emulated encapsulation, Angular adds generated attributes to a component's elements and rewrites its selectors to match them. A rule in a parent component's stylesheet such as app-card .title { color: red; } does not reach the elements inside app-card's template, because those elements carry the child's attribute, not the parent's.
That isolation is useful, but it leaves a gap. A reusable component usually needs a few knobs that consumers can change, such as a background color, a padding or a border radius. Reaching for ::ng-deep or ViewEncapsulation.None solves this by removing isolation. CSS custom properties solve it without removing anything.
What a custom property is
A CSS custom property is a name that starts with two dashes, such as --card-background. You set it like any other property and read it with the var() function.
.panel {
--accent: teal;
border: 1px solid var(--accent);
}Two features make custom properties suited to theming across boundaries:
- They inherit by default. A value set on an element is available to all of its descendants.
- They are resolved at runtime in the browser, so changing a value updates every place that reads it.
Encapsulation rewrites selectors, so it controls which rules apply to which elements. It does not stop inheritance. Inheritance follows the DOM tree, and a child component's elements are descendants of the host element in that tree. This is why a value set on the app-card host element flows into the card's own encapsulated styles.
Designing a component with theme hooks
The component declares which properties it reads, and gives each one a fallback so the component looks right with no outside configuration.
import { Component, input } from '@angular/core';
@Component({
selector: 'app-card',
template: `<ng-content />`,
styles: `
:host {
display: block;
padding: var(--card-padding, 16px);
background: var(--card-background, white);
}
:host(.highlighted) {
outline: 2px solid orange;
}
`,
host: {
'[class.highlighted]': 'highlighted()',
},
})
export class CardComponent {
highlighted = input(false);
}The second argument to var() is the fallback. If --card-padding is not defined anywhere above the card in the DOM, the browser uses 16px. The host metadata binds the highlighted class on the host element, and :host(.highlighted) styles it. The :host selector and host bindings are covered in their own chapters, so treat them here as the way the card styles its own outer element.
Setting the properties from outside
A global stylesheet can set the properties on the element selector:
/* styles.css (global) */
app-card {
--card-background: #f8fafc;
--card-padding: 24px;
}This rule works even though it is global and the card is encapsulated. The rule matches the app-card host element, which is in the parent's scope. It does not try to reach inside the card's template. The two properties then inherit down into the card's template, where var() reads them.
A parent component can do the same in its own styles, because the app-card element in the parent's template carries the parent's attribute:
import { Component } from '@angular/core';
import { CardComponent } from './card.component';
@Component({
selector: 'app-dashboard',
imports: [CardComponent],
template: `
<app-card class="warning">Disk space is low.</app-card>
<app-card>All systems normal.</app-card>
`,
styles: `
.warning {
--card-background: #fef3c7;
--card-padding: 32px;
}
`,
})
export class DashboardComponent {}Only the first card gets the new values. The second card falls back to its defaults. A property set on one element affects that element and its descendants, so you can theme one instance, one section of a page, or the whole application by choosing where to set it.
Why this works with each encapsulation mode
The table compares how custom properties behave under each mode.
| Mode | Can outside selectors style inner elements? | Do custom properties reach inner elements? |
|---|---|---|
| Emulated | No, selectors are scoped by attribute | Yes, by inheritance |
| ShadowDom | No, the shadow root blocks selectors | Yes, custom properties inherit through the shadow boundary |
| None | Yes, styles are global | Yes |
The ShadowDom row is the important one. A shadow root blocks ordinary selectors from the outside. Inheritable properties, which include custom properties, still pass through. This is the standard mechanism that web components use to expose theming hooks, so the pattern in this chapter works the same whether you choose Emulated or ShadowDom.
Global theme tokens on `:root`
For an application-wide theme, define tokens on :root, which is the html element, and let components read them:
/* styles.css (global) */
:root {
--color-surface: #ffffff;
--color-text: #1f2937;
--color-accent: #4f46e5;
--radius: 6px;
}
:root[data-theme='dark'] {
--color-surface: #111827;
--color-text: #f9fafb;
--color-accent: #818cf8;
}A component reads the tokens without knowing which theme is active:
import { Component } from '@angular/core';
@Component({
selector: 'app-alert',
template: `<p class="alert"><ng-content /></p>`,
styles: `
.alert {
color: var(--color-text);
background: var(--color-surface);
border-left: 4px solid var(--color-accent);
border-radius: var(--radius);
padding: 8px 12px;
}
`,
})
export class AlertComponent {}Switching the theme is then a single change on one element. You do not have to touch any component styles:
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-theme-toggle',
template: `<button (click)="toggle()">Theme: {{ theme() }}</button>`,
})
export class ThemeToggleComponent {
theme = signal<'light' | 'dark'>('light');
toggle() {
this.theme.update((t) => (t === 'light' ? 'dark' : 'light'));
document.documentElement.dataset['theme'] = this.theme();
}
}Every component that reads --color-surface updates at once, because the browser recomputes the styles that depend on the changed value.
Setting properties from component state
Sometimes the value comes from your data rather than from a stylesheet. A style binding can set a custom property on an element:
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-tag',
template: `
<span class="tag" [style.--tag-color]="color()">
<ng-content />
</span>
`,
styles: `
.tag {
padding: 2px 8px;
border: 1px solid var(--tag-color, gray);
color: var(--tag-color, gray);
}
`,
})
export class TagComponent {
color = signal('crimson');
}Angular supports custom property names in [style.--name] bindings. This keeps the stylesheet static and moves only the changing value into the template, which is easier to maintain than building a style string.
Common errors and gotchas
- No fallback. If you write
var(--card-padding)with no fallback and nothing defines the property, the declaration is invalid at computed-value time. The property then behaves asunset, which often means no padding at all. Always provide a default for values the component owns. - Setting the property on the wrong element. A custom property only reaches descendants. Setting
--card-backgroundon a sibling or on a child inside the card has no effect on the card host. Set it on the host or on any ancestor. - Name collisions. Custom properties share one namespace for the whole DOM subtree. A generic name like
--colorcan be overwritten by an unrelated ancestor. Prefix component-specific hooks, for example--card-, and keep application tokens in a documented set. - Using them where they do not apply. Custom properties hold values, not selectors or property names. You cannot write
var(--prop): redor put them inside a media query condition. - Specificity surprises. The rule that sets the property still follows the normal cascade. A global
app-card { --card-padding: 24px; }can lose to a more specific selector, or to a component style that itself sets--card-paddingon:host. If a component sets its own value on:host, it overrides inherited values for its own subtree. - Overriding inherited values with
:host. Do not set a hook on:hostif the intent is to let the outside configure it. Use thevar()fallback for the default and leave the property undefined.
When to use custom properties
Custom properties fit best when the component author decides what can change. The set of hooks is small, named and documented, so consumers cannot depend on the component's internal class names. If a consumer needs to restyle something the component does not expose, that is a signal to add a hook rather than to pierce encapsulation.
They have limits. They carry values, so they cannot add a new rule, hide an element conditionally or restyle a third-party component that exposes no hooks. For third-party markup you do not control, the later chapters on ::ng-deep and ViewEncapsulation.None describe the trade-offs.
Exercise
A app-button component styles its inner <button> with background: var(--btn-bg) and no fallback. A page uses <app-button> without setting --btn-bg, and the button renders with no background. Explain why, and give two changes that fix it: one inside the component and one in a global stylesheet.
Show answer
With no value defined on the host or any ancestor, var(--btn-bg) has no fallback, so the declaration is invalid at computed-value time and the property acts as unset, which gives a transparent background. Inside the component, add a fallback: background: var(--btn-bg, #4f46e5);. In a global stylesheet, define the property on the host or on :root: app-button { --btn-bg: #4f46e5; }. The value inherits into the component's encapsulated template, so the rule works even though the stylesheet is global.
Exercise
Under Emulated encapsulation, a global rule app-card .title { color: red; } has no effect on a .title element inside app-card's template. Why does app-card { --title-color: red; } still work if the card's styles contain .title { color: var(--title-color, black); }?
Show answer
The selector app-card .title is scoped by Angular's generated attributes, so it cannot match elements that carry only the card's attribute in the way the global rule needs. Selector matching is what encapsulation controls. The second rule matches only the app-card host element, which is reachable from outside, and it sets a custom property. Custom properties inherit through the DOM tree, so .title inside the card receives the value, and the card's own scoped rule applies it.
Exercise
You add a dark theme by writing :root[data-theme='dark'] { --color-surface: #111827; }. A component still shows a white background after the attribute is set. List two likely causes.
Show answer
First, the component may hard-code a color instead of reading var(--color-surface), so the token never applies. Second, an element between :root and the component may redefine --color-surface, for example in a :host rule or a global rule on the component's selector, which overrides the inherited dark value for that subtree. Also check that the attribute is set on the html element, because :root matches only that element.