skills/dev-skills/angular-developer/references/component-styling.md
Angular components can define styles that apply specifically to their template, enabling encapsulation and modularity.
Styles can be defined inline or in separate files.
@Component({
selector: 'app-photo',
// Inline styles
styles: `
img {
border-radius: 50%;
}
`,
// OR external file
styleUrl: 'photo.component.css',
})
export class Photo {}
Every component has a view encapsulation setting that determines how styles are scoped.
| Mode | Behavior |
|---|---|
Emulated (Default) | Scopes styles to the component using unique HTML attributes. Global styles can still leak in. |
ShadowDom | Uses the browser's native Shadow DOM API to isolate styles completely. |
None | Disables encapsulation. Component styles become global. |
ExperimentalIsolatedShadowDom | Strictly guarantees that only the component's styles apply. |
import { ViewEncapsulation } from '@angular/core';
@Component({
...,
encapsulation: ViewEncapsulation.None,
})
export class GlobalStyled {}
:hostTargets the component's host element (the element matching the component's selector).
:host {
display: block;
border: 1px solid black;
}
:host-context()Targets the host element based on some condition in its ancestry.
/* Apply styles if any ancestor has the 'theme-dark' class */
:host-context(.theme-dark) {
background-color: #333;
}
::ng-deepDisables view encapsulation for a specific rule, allowing it to "leak" into child components.
Note: The Angular team strongly discourages the use of ::ng-deep. It is supported only for backwards compatibility.
You can use <style> elements directly in a component's template. View encapsulation rules still apply.
<style>
.dynamic-class {
color: red;
}
</style>
<div class="dynamic-class">Hello</div>
Using <link> or @import in CSS is treated as external styles. External styles are not affected by emulated view encapsulation.