Encapsulating CSS styling
When you build a component, you want its styles to be modular. Angular provides three strategies to handle how CSS is applied to the DOM. You can control this using the encapsulation property in the @Component decorator.
1. The Default: ViewEncapsulation.Emulated
By default, Angular does not use the real Shadow DOM (which can be incompatible with older browsers). Instead, it emulates it. It adds a unique attribute (like _ngcontent-a-1) to your component's HTML elements and modifies your CSS selectors to match that attribute.
Step-by-Step Example
Step A: Create a Service Card Component
We want this card to have a specific border.
src/app/service-card/service-card.component.css
src/app/service-card/service-card.component.html
The Result: Even though we used a general div selector, it will not affect any other div outside of this component. Angular "sandboxes" the style.
2. Breaking the Walls: ViewEncapsulation.None
Sometimes, you want a component to provide global styles (for example, a "Theme Switcher" component). In this case, you can turn off encapsulation.
Step-by-Step Example
Step A: Modify the Component Logic
We tell Angular to stop scoping the styles.
src/app/service-card/service-card.component.ts
The Result: The moment this component is loaded, every div in your entire application (including the index.html and other components) will suddenly have a blue border. The styles "leak" out into the global scope.
3. The Modern Standard: ViewEncapsulation.ShadowDom
This uses the browser's native Shadow DOM API. It creates a completely isolated DOM tree for the component.
- Isolation: Global styles from your
styles.csswill not enter the component. - Encapsulation: The component's styles will not leave the component.
- Support: Requires a modern browser that supports Web Components.
TypeScript
Summary Comparison
| Strategy | Behavior | Best Used For... |
Emulated (Default) | Scopes CSS using unique HTML attributes. | 95% of all Angular development. |
None | Styles are global and affect the whole app. | Global themes or third-party style overrides. |
ShadowDom | Uses the browser's native isolation. | Creating truly independent Web Components. |
Pro-Tips for Style Management
- Stick to the Default: Always start with
Emulated. It provides the best balance between performance and safety. - Avoid Tag Selectors: Even with encapsulation, it is better practice to use classes (e.g.,
.card-container) instead of tags (e.g.,div). This makes your CSS more readable and specific. - The
:hostSelector: If you want to style the component's actual tag (the<app-service-card>itself), use the special:hostselector in your CSS: