问题
In a recent Angular 7 project, I have a component (defined in the file file-list.component.ts
) in which there is a mat-paginator
(a component from Angular material component library). When I want to change the background color of the mat-paginator
, I first tried to put
.mat-paginator-container {
background-color: yellow;
}
in film-list.component.scss
(the stylesheet for associated with this component), the background color of the paginator did not change. When I put this in app.component.scss
, it did not work either. But when I put it in the src/styles.css
, the background color is correctly changed.
So my questions are:
- What is the difference between
src/styles.scss
,app.component.scss
andfilm-list.component.scss
? - What is the scope of each of these files?
- What is the influence of
body
selector used in these stylesheet files?
回答1:
src/styles.scss
Is for global CSS that will be applied across all the application and all the components. Here you can apply styling to body
without problem.
example.component.scss
Is the CSS that will be scoped and applied to this specific component only. Here you won't be able to apply styling to body
element.
You can still pierce the scoped boundaries...
When using components like mat-paginator
inside, let say example.component.ts
for example, the CSS from mat-paginator
is in fact "outside" the example.component.ts
component scope because mat-paginator
has its own scope. Therefore you can pierce through the shadow-dom using ::ng-deep to apply CSS.
Working example with the code below: https://stackblitz.com/edit/angular-stackoverflow-53241725
/* not working because the class is not directly inside this component */
.mat-paginator-container {
background: yellow;
}
/* working because `ng-deep` pierce through the shadow-dom */
::ng-deep .mat-paginator-container {
background: red;
}
Suggested Documentation
Official Angular documentation about styling: https://angular.io/guide/component-styles
Great blog that explains CSS encapsulation: https://blog.angular.io/the-state-of-css-in-angular-4a52d4bd2700
来源:https://stackoverflow.com/questions/53241725/difference-between-global-scss-file-and-scss-file-for-component-in-angular