Scoped CSS by Default
Component Styles & View Encapsulation
A component's styles only affect that component — Angular adds unique attributes to scope them at build time.
What you'll learn
- Inline styles vs styleUrls
- Emulated vs ShadowDom vs None
- Use :host and :host-context
Angular components get scoped CSS for free. The default behaviour is good enough for most apps, but it is worth knowing how it works.
Inline vs External Styles
import { Component } from '@angular/core';
@Component({
selector: 'app-card',
standalone: true,
styles: `
.title { font-weight: 700; }
p { color: #555; }
`,
template: `<h2 class="title">Card</h2><p>Body</p>`,
})
export class CardComponent {} For longer stylesheets, point at a file with styleUrl: './card.css' (or styleUrls: [...] for several).
The Three Encapsulation Modes
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-card',
standalone: true,
encapsulation: ViewEncapsulation.Emulated, // default
// ...ShadowDom — real shadow DOM, true isolation
// ...None — styles bleed everywhere (global)
})
export class CardComponent {} Emulated rewrites your CSS at build time, adding [_ngcontent-xyz] attributes to selectors. That gives you scoping without paying the shadow-DOM tax.
Styling the Host
Use the :host selector to style the component’s outer element.
:host {
display: block;
border: 1px solid #ddd;
}
:host(.active) {
border-color: dodgerblue;
}
:host-context(.dark) {
background: #111;
color: #eee;
} :host(.active) matches when the host itself has the .active class. :host-context(.dark) matches when any ancestor up the tree has .dark — great for theme inheritance.