In a standard HTML/CSS website, a class defined in one file can easily bleed into another page and break the layout.
Angular solves this massive headache by scoping CSS styles directly to the component they belong to!
Styles defined inside an Angular component will strictly affect that component and absolutely nothing else.
Behind the scenes, Angular implements CSS scoping by attaching unique attributes to your HTML elements.
When the app compiles, it translates your standard CSS classes into highly specific attribute selectors (like _ngcontent-c1).
This emulates the behavior of the Shadow DOM, keeping your global styles perfectly clean.
You can define your component's CSS in two ways within the @Component decorator.
For tiny, single-line styles, use the styles array.
For larger blocks of CSS, link to an external file using the styleUrls array.
@Component({
selector: 'app-alert',
template: '<h1 class="title">Warning!</h1>',
// Inline styling strictly scoped to this component
styles: ['.title { color: red; font-size: 24px; }']
})
export class AlertComponent {}
Angular allows you to control how tightly your CSS is scoped using View Encapsulation modes.
By importing ViewEncapsulation from @angular/core, you can change the scoping behavior.
Emulated (Default): Styles are scoped to the component using generated attributes.None: Scoping is completely disabled; styles bleed out globally to the entire application.ShadowDom: Uses the browser's native Shadow DOM API to encapsulate styles.
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-global-widget',
template: '<p class="global-text">I bleed globally!</p>',
styleUrls: ['./global-widget.component.css'],
// Disables scoping entirely for this specific component
encapsulation: ViewEncapsulation.None
})
export class GlobalWidgetComponent {}
Sometimes, you need to apply CSS styles directly to the component's host element itself, rather than the elements inside it.
Because the host element (e.g., <app-root>) is technically owned by the parent component, you cannot style it directly using normal CSS tags.
To target the host element from within the component's own stylesheet, use the :host pseudo-class selector.
/* Inside your component's .css file *//* Styles the component's outer custom HTML tag directly */ :host { display: block; border: 2px solid blue; padding: 20px; }
/* Styles the host ONLY if it also has the 'active' class */ :host(.active) { background-color: lightblue; }
What is the default View Encapsulation mode in Angular?
Which special CSS selector allows you to style the component's custom HTML element tag from within its own stylesheet?