Home >Web Front-end >CSS Tutorial >How to Style Child Components from a Parent Component's CSS in Angular?

How to Style Child Components from a Parent Component's CSS in Angular?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-26 01:00:09778browse

How to Style Child Components from a Parent Component's CSS in Angular?

How to Style Child Components from Parent Component's CSS File?

In Angular, styling child components from a parent component's CSS file requires a way to pierce through component scoping. Here's how to overcome this limitation.

Update (Angular 4.3.0 and Above)

With the deprecation of piercing CSS combinators, a new one, ::ng-deep, was introduced. It allows you to target child components deep within the DOM structure.

:host ::ng-deep parent {
  color: blue;
}
:host ::ng-deep child {
  color: orange;
}

Old Way (Angular Versions Prior to 4.3.0)

Before ::ng-deep, you could use piercing CSS combinators such as >>>, /deep/, and ::shadow to penetrate component boundaries. However, note that these combinators are deprecated and should be avoided if possible.

:host >>> parent {
  color: blue;
}
:host >>> child {
  color: orange;
}

Alternative Approaches

  • Encapsulation Mode: By default, components are encapsulated using the Shadow DOM, preventing styles from leaking outside the component. You can disable encapsulation by setting the encapsulation property to None in the component decorator (@Component).
  • styleUrls: Use the styleUrls property in the child component to import styles from the parent component. This allows you to access the parent component's stylesheet within the child component's scope. However, this approach requires manually defining styles for child components in the parent's stylesheet.

The above is the detailed content of How to Style Child Components from a Parent Component's CSS in Angular?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn