在顶层组件的样式块中,我定义了一个/deep/
css类,用于设置将出现在其ng-content中的任何项的边距。如何才能使css类具有优先权-即使子组件应用其自己css类并定义了不同的页边距。
例如:
ParentComponent.ts:
@Component({
selector: 'my-parent',
styles: [`
/deep/ .child-item { /* I WANT THIS TO TAKE PRECEDENCE */
margin-right: 10px;
margin-left: 10px;
}
`],
template: `
<div>
<ng-content></ng-content>
<div>
`
})
export class ParentComponent {}
ChildComponent.ts
@Component({
selector: 'my-child',
styles: [`
.less-important-class { /* THESE MARGINS SHOULD BE IGNORED IN CONFLICTS */
margin-right: 5px;
margin-left: 5px;
background-color: rgba(255, 0, 0, 1.0);
}
`],
template: `
<button type="button" class="less-important-class child-item">My Little Button</button>
`
})
export class ChildComponent {}
我认为由于子项首先出现在已编译的样式表中,次要类具有更高的css特异性,并在两个类之间的任何冲突中胜出。如何才能给子项更高的优先级?
发布于 2016-10-06 23:19:47
/deep/用于重写父级样式,因此假设您想要更改父级中div的页边距,可以使用/deep/ { style:**px}
据我所知,当你不想让父组件干扰子组件的样式时,你会在子组件中定义样式。如果您希望父元素的样式优先,那么我建议您不要在子元素中定义这些样式。这意味着在您的例子中,不要在在子组件中定义的样式中指定边距。
另一种方法是不在父样式和子样式中定义这些stlyes,而是创建一个新的全局样式表,并只添加全局样式。当然,您需要在index.html中引用该样式表,因此在本例中,我将从父样式和子样式中删除页边距,并将其添加到styles.css中,并在index.html中引用styles.css
https://stackoverflow.com/questions/39905689
复制