Sub topic 6
Global styles and where they belong
This chapter assumes you know basic CSS (selectors, specificity, the cascade) and can write a standalone Angular component. It also assumes you have read the chapter on Emulated encapsulation. Here you will learn what belongs in the application's global stylesheet, how Angular loads it, and how it interacts with scoped component styles.
What a global style is
A global style is CSS that is not attached to any component. Angular does not rewrite its selectors, so it can match any element in the document, including elements inside component templates.
A component's styles or styleUrl metadata works differently under the default Emulated mode. Angular adds a generated attribute such as _ngcontent-abc-c12 to every element in the template. It also rewrites each selector to require that attribute, so .label becomes roughly .label[_ngcontent-abc-c12]. A global stylesheet gets no such rewrite.
The effect is asymmetric:
- Global rules reach into every component, because they have no attribute requirement.
- Component rules stay inside their own template.
Where global styles are registered
The Angular CLI reads global stylesheets from the styles array of the build target in angular.json. A new project already has src/styles.css (or .scss) listed there.
{
"projects": {
"demo": {
"architect": {
"build": {
"options": {
"styles": [
"src/styles.css",
{
"input": "src/themes/dark.css",
"bundleName": "dark",
"inject": false
}
]
}
}
}
}
}
}This is a fragment of angular.json, not a full file. The first entry is injected into the page automatically. The second is built into its own dark.css bundle but is not injected, because inject: false is set. You would load it yourself later, for example by adding a <link> element when the user picks a dark theme.
You could also add a <link rel="stylesheet"> to index.html. That works, but the file then bypasses the build pipeline. It is not bundled, minified, or given a content hash for cache busting, and Sass is not compiled. Prefer the styles array for anything you author.
Stylesheets also work from node_modules. A path such as node_modules/some-library/dist/library.css is a valid entry, which is how many third-party UI libraries ship their base styles.
What belongs in the global stylesheet
A good global stylesheet is small and covers concerns that really are application-wide:
- Resets and base element styles. Box sizing, body margin, default font, link color.
- Design tokens as custom properties. Colors, spacing, radii, and font sizes declared on
:root. - Typography. Heading sizes and line height, if you want them consistent everywhere.
- Utility classes. A handful of single-purpose classes (
.visually-hidden,.stack) that many components use. - Third-party styles. Library themes and icon fonts that expect to be global.
- Rules for content you do not control. For example, HTML rendered with
[innerHTML], which carries no Emulated attribute (see below).
Here is a compact example:
/* src/styles.css */
:root {
--color-text: #1f2937;
--color-surface: #ffffff;
--color-accent: #4f46e5;
--space-2: 8px;
--space-4: 16px;
--radius: 4px;
}
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
margin: 0;
font-family: system-ui, sans-serif;
color: var(--color-text);
background: var(--color-surface);
}
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}A component can then consume the tokens without importing anything:
import { Component } from '@angular/core';
@Component({
selector: 'app-notice',
template: `<p class="notice"><ng-content /></p>`,
styles: `
.notice {
padding: var(--space-2) var(--space-4);
border-left: 4px solid var(--color-accent);
border-radius: var(--radius);
}
`,
})
export class NoticeComponent {}Custom properties inherit through the DOM, so they cross the encapsulation boundary. Only selectors are scoped, not inherited values. This is why tokens are the preferred way for global styles to influence components.
What does not belong there
Rules that describe one component's internals should stay in that component. Suppose you write .title { font-size: 2rem; } globally. Every .title in every template now changes, including ones in components you add next year. You lose the main benefit of Emulated encapsulation, which is that you can read a component's styles without searching the whole application.
A practical test: if you would have to delete the rule when you delete one specific component, it belongs in that component.
How global and component styles interact
Two forces decide which rule wins: specificity and source order.
Specificity
Emulated encapsulation adds an attribute selector to every component rule. That raises the rule's specificity by one class-level step. A component rule .label therefore beats a global .label that has the same selector shape, regardless of order. Global rules do not accidentally override component rules that are written the same way.
A global rule with more specific selectors can still win. For example, body .label is more specific than .label[_ngcontent-abc-c12], so the global rule overrides the component.
Order
When specificity ties, the later rule wins. Angular appends component styles to the document <head> as components are first created, so they usually come after the global stylesheet. Do not depend on that, since lazy loading changes when component styles arrive. Make the rule win through selector design, not load order.
Encapsulation mode changes the picture
| Mode | Global styles reach the component? | Component styles leak out? |
|---|---|---|
| Emulated (default) | Yes | No |
| None | Yes | Yes, the styles become global |
| ShadowDom | No, except inherited properties and custom properties | No |
With ViewEncapsulation.None, the component's styles are added unmodified, so they behave like global styles that happen to load with the component. With ShadowDom, the global stylesheet stops at the shadow root. Only inheritable properties (such as color and font-family) and custom properties get through.
Common problems
Global styles seem to be ignored
First check whether the component uses ShadowDom. If it does, the global selector cannot match inside the shadow root. Move the value into a custom property that the component reads, or add the rule to the component.
If the component is not in ShadowDom mode, check specificity. A component rule with an attribute selector may be overriding your global rule.
The stylesheet is not loaded
If a new global file has no effect, confirm it is listed in the styles array of the correct build configuration. Then restart the dev server, because changes to angular.json are not picked up by a running server.
Styles do not apply to `[innerHTML]` content
HTML inserted with [innerHTML] does not receive the Emulated attribute, because Angular did not render those elements from your template. A component rule such as .content a { color: red; } therefore does not match them. The usual fixes are a global rule scoped to a wrapper class, or :host ::ng-deep as a last resort. A global rule is the safer choice.
/* src/styles.css */
.rich-text a {
color: var(--color-accent);
text-decoration: underline;
}import { Component, input } from '@angular/core';
@Component({
selector: 'app-article-body',
template: `<div class="rich-text" [innerHTML]="html()"></div>`,
})
export class ArticleBodyComponent {
html = input.required<string>();
}Angular sanitizes [innerHTML] values. Styling is only one reason to treat that content carefully.
Global CSS grows into a second application
Teams often start with a few helpers and end with thousands of lines of cross-cutting selectors. Signs of trouble are selectors that mention component names (app-card .title) and !important used to win fights between files. Move those rules into the components they describe, and pass variation through custom properties or inputs.
Organizing the global stylesheet
With Sass, split the global file into partials and import them from one entry file. Using @use keeps the output order predictable.
// src/styles.scss
@use './styles/tokens';
@use './styles/base';
@use './styles/utilities';Use this order: tokens, then base, then utilities. Utilities come last so they can override base rules. Components then sit on top, with scoped rules that handle their own layout.
If you need shared Sass variables or mixins inside component styles, add a directory to stylePreprocessorOptions.includePaths in angular.json. You can then import by short path instead of long relative ones. Sass variables exist only at build time. Anything that must change at runtime, such as switching themes, should be a custom property.
Decision criteria
Ask these questions in order for any new rule:
- Does it describe one component's own template? Put it in that component.
- Is it a value that varies by theme or context? Declare a custom property globally and read it in the component.
- Does it style elements Angular did not render (
[innerHTML], third-party widgets)? Use a global rule under a wrapper class. - Does it apply to nearly every element (reset, typography)? Put it in the global stylesheet.
Exercise
A component app-tag uses ViewEncapsulation.ShadowDom. Your global styles.css has .tag { background: gold; }, and the component template contains <span class="tag">, but the background stays unchanged. Give the cause and one fix that keeps the component isolated.
Show answer
A shadow root blocks global selectors, so .tag in the global stylesheet cannot match the span inside it. Only inherited properties and custom properties cross the boundary. The fix is to declare a custom property such as --tag-background: gold; globally, for example on :root or on app-tag. The component then reads it with background: var(--tag-background, lightgray); in its own styles.
Exercise
A global rule .label { color: red; } and a component rule .label { color: blue; } target the same element under Emulated encapsulation. Which color wins, and why? Then name a global selector that would win.
Show answer
Blue wins. Emulated encapsulation rewrites the component rule to .label[_ngcontent-xxx], which has higher specificity than the bare global .label, so load order does not matter. A global selector such as body .label has higher specificity than the rewritten component rule, so it would win and turn the text red.