Overriding the encapsulated CSS of external compon

2019-06-16 19:23发布

I was wondering how to override the encapsulated CSS of an external component.

So I am using material2 in my project and the tabs component has a the attribute overflow set on tab-body. Is it possible to override the overflow value?

3条回答
女痞
2楼-- · 2019-06-16 20:08

Just check the class that is being applied to the tabs by the external component (use Inspector or any other tool). In your style css file, add the same name of the class for the tabs and set the overflow property along with adding !important to it to make sure it overwrites the previous one. Also make sure your css link to the page is added after the external component css link if any.

Hope this helps.

查看更多
时光不老,我们不散
3楼-- · 2019-06-16 20:10

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.

查看更多
甜甜的少女心
4楼-- · 2019-06-16 20:11

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.

查看更多
登录 后发表回答