As we have seen in the previous chapters, the styles.css file in an Angular project contains styles that are applied globally across the entire application. This means any styles defined here will affect all components unless overridden.
Typically is used for base styles, theming, or styles that should be consistent across the application, such as typography, global layout, and default styles for HTML elements.
Styles defined within the styles or styleUrl properties of an Angular component are scoped to that component.
This means they only apply to the component's template and not to other components or elements.
This can be very useful for defining styles that are specific to a component, ensuring that these styles do not leak out and affect other parts of the application.
Angular provides three strategies for view encapsulation that determine how styles are applied to components and whether styles leak outside the component:
This strategy is the default of any Angular component and ensures component styles are encapsulated while being broadly compatible with existing browsers.
Styles are scoped to the component using special generated attributes.
The styles are applied only to the component's view but use standard CSS without requiring shadow DOM .
How it works?
Behind the scene, at compile time, Angular adds a unique attribute to the component's elements and styles, such as _ngcontent-abc.
It means that the rendered HTML should looks like the following:
and the rendered css will be similar to the following:
Let me show an example.
This is typical Angular root component and it uses the default encapsulation
You can define this strategy through the encapsulation: ViewEncapsulation.Emulated property of the @Component decorator but it is not necessary now since it is the default option.
src/app.component.ts
Output
This is the generated output.
The HTML elements of the component have a unique attribute _ngcontent-ng-c2412767270 and the style block generated by Angular creates the CSS classes that can only be applied to those elements:
If you now create another component in the application that define again .title and .body classes, you'll be sure there won't conflicts because the generated classes will be different (we'll talk about components in next chapters)