CSS 样式不适用于子组件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38798002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Styling not applying to child component
提问by Varun
I'm trying to apply styling to a child component tag, but I can't do that.
我正在尝试将样式应用于子组件标记,但我不能这样做。
I have child component with anchor tag.
我有带有锚标记的子组件。
Even though i have styling for anchor tag in the parent component, it's not applying. What's the solution for it?
即使我在父组件中设置了锚标记的样式,它也不适用。它的解决方案是什么?
Working code: http://plnkr.co/edit/CJCpV4ZbG7hdxT2AeSmt?p=preview
工作代码:http: //plnkr.co/edit/CJCpV4ZbG7hdxT2AeSmt?p=preview
<a href="https://www.google.com">Google</a>
In the parent component i'm using the child component and applying styling for this child component.
在父组件中,我使用子组件并为此子组件应用样式。
Html code:
html代码:
<div class="container">
<div class="test">
<testapp></testapp>
</div>
</div>
Css code:
css代码:
.container{
font-family:sans-serif;
font-size:18px;
border: 1px solid black;
}
.test{
width:50%;
background-color:#f0f5f5;
}
.container:hover .test{
background-color:#e6ffe6;
}
.container:hover .test:hover{
background-color:#ffffe6;
}
.container .test a {
color: red ;
}
.container .test a:hover {
color:green;
}
回答by Thierry Templier
It's because by default components have view encapsulation (shadow dom). To disable this behavior, you can leverage the encapsulation
attribute, as described below:
这是因为默认组件具有视图封装(shadow dom)。要禁用此行为,您可以利用该encapsulation
属性,如下所述:
import {Component, ViewEncapsulation} from '@angular/core';
import {TestApp} from 'testapp.component.ts';
@Component({
selector:'test-component',
styleUrls: ['test.component.css'],
templateUrl: './test.component.html',
directives:[TestApp],
encapsulation: ViewEncapsulation.None // <------
})
export class TestComponent{
}
See this plunkr: http://plnkr.co/edit/qkhkfxPjgKus4WM9j9qg?p=preview.
请参阅此 plunkr:http://plnkr.co/edit/qkhkfxPjgKus4WM9j9qg?p=preview 。
回答by DeborahK
When using the styleUrls property, the styles are localto the one component, not to its children. So I made two changes: 1) Moved the styleUrls to the testapp component. 2) Moved the div to the testapp component.
使用 styleUrls 属性时,样式是一个组件的本地样式,而不是它的子组件。所以我做了两个改变:1)将 styleUrls 移动到 testapp 组件。2) 将 div 移动到 testapp 组件。
import {Component} from '@angular/core';
@Component({
selector:'testapp',
styleUrls: ['./test.component.css'],
template: `
<div class="test">
<a href="https://www.google.com">Google</a>
</div>
`
})
export class TestApp{
}
回答by RPD
EDITED: This should solve:
编辑:这应该解决:
In the css of child class write below code
在子类的css中写下面的代码
:host.parentclass childclass{
}
The parentclass is immediate parent of child. childclass is the class applied to child component.
父类是孩子的直接父类。childclass 是应用于子组件的类。