Overriding the encapsulated CSS of external component

From this article

Although the style of a component is well isolated, it can still be easily overridden if necessary. For that, we just need to add an attribute to the body of the page:

<body override>
    <app></app>
</body>

The name of the attribute can be anything. No value is needed and the name override makes it apparent what its being used for. To override component styles, we can then do the following:

[override] hello-world h1 {
    color:red;
}

Where override is the attribute, hello-world is the target component, and h1 is whatever you are trying to restyle. (get this right or it wont work).

Your component hello-world would be

selector: 'hello-world',
styles: [`
   h1 {
      color: blue;
   }
`],
template: ` <h1>Hello world</h1> `

I think this is the most elegant way.


Alternatively if you are building a library of some sort, you can reset the styling altogether by doing something fancy in your css like:

:host-context(.custom-styles) { //.. css here will only apply when there is a css class custom-styles in any parent elem }

So then to use your component you'd use

<hello-world class="custom-styles">

But this is way less convenient than the first option.


You can use the special css /deep/ instruction. See the documentation

So, if you have

app
  sub-component
    target-component
      <div class="target-class">...</div>

You can put in your apps css (or less):

/deep/ .target-class {
  width: 20px;
  background: #ff0000;
}

Obviously, you can put this css fragment in sub-component as well.