I have very basic, and reusable css rules, such as:
.ng-invalid {
border-left: 5px solid #a94442;
}
.ng-valid {
border-left: 5px solid #42A948;
}
I'd like to re-use these for all of my components. If I place this in my root AppComponent
, which is the one that is bootstrapped by Angular, then it's not recognized by any other components in my application other than the AppComponent
.
I must be missing something very obvious here.
Everything about CSS applies to Angular components. We can also compound component styles with components, which allows for more modular designs than regular stylesheets. We can define CSS styles in addition to template content in our components. One way to do it is to use the styles property in our component.
Component Styles Learn how to apply CSS styles to components. Angular applications are styled with standard CSS. That means you can apply everything you know about CSS stylesheets, selectors, rules, and media queries directly to Angular applications.
Angular applications are styled with standard CSS. That means you can apply everything you know about CSS stylesheets, selectors, rules, and media queries directly to Angular applications. Additionally, Angular can bundle component styleswith components, enabling a more modular design than regular stylesheets.
The content is likely still applicable for all Angular 2 + versions. CSS encapsulation has always been something developers have wanted in their web applications. The ability to scope CSS to a specific component without affecting other components has been difficult to achieve.
You can write your CSS inside src/styles.css
or you can create your new CSS file and specify inside .angular-cli.json file
"apps": [
"styles": ["styles.scss"]
]
Angular adds unique classes to your component and rewrites the selectors of CSS added to components to only match that components unique class, before adding the CSS to the <head>
. This is to emulate shadow DOM style encapsulation.
You can work around it by
set encapsulation: ViewEncapsulation.None
which prevents rewriting styles for components where encapsulation is disabled
add the CSS to the index.html
directly. Angular doesn't rewrite CSS that is not added to components.
use "shadow piercing CSS combinator" ::ng-deep someSelector { ... }
which also makes the CSS ignore the unique classes added to the components.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With