【问题标题】:How can I make an Angular2 "deep" css class take precedence?如何让 Angular2“深度”css 类优先?
【发布时间】:2017-02-15 18:30:22
【问题描述】:

在我的顶级组件的样式块中,我定义了一个/deep/ css 类,它为将出现在其 ng-content 中的任何项目设置边距。如何使该 css 类优先 - 即使子组件应用其自己的定义了不同边距的 css 类。

例如:

父组件.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 {}

子组件.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 {}

我认为由于 child-item 首先出现在编译的样式表中,less-important-class 具有更高的 css 特异性,并且在两个类之间的任何冲突中胜出。如何给子项更高的优先级?

【问题讨论】:

  • 与往常一样,您可以使用!important 为属于不太具体的选择器(深层)的规则赋予更高的优先级。
  • 添加 !important 在这种情况下没有帮助,因为 Angular 的工作方式确保子组件样式优先于您所做的任何事情。
  • 我发现在 /deep/ css 类之前使用 :host 选择器使该类优先于子组件中定义的 css 类。只要这些组件没有使用:host 选择器。

标签: css angular typescript angular2-template css-specificity


【解决方案1】:

/deep/ 用于覆盖父母的风格,所以说你想改变父母中 div 的边距,你可以使用 /deep/ {margin: **px}

据我所知,当您不希望父组件干扰子组件的样式时,您会在子组件中定义样式。如果您希望父母的风格优先,那么我会说不要在孩子中定义这些风格。这意味着在您的情况下,不要在子组件中定义的样式中指定边距。

另一种方法是不要在 Parent 或 child 中定义这些样式,而是创建一个新的全局样式表并只添加全局样式当然你需要在 index.html 中引用该样式表所以在你的情况下,我会从父母和孩子的样式并将其添加到styles.css并在index.html中引用styles.css

【讨论】:

  • 在文档中说We can use the /deep/ selector to force a style down through the child component tree into all the child component views. The /deep/ selector works to any depth of nested components, and it applies both to the view children and the content children of the component.
  • 但是我明白你在说什么。我的问题是有时子组件出现在父组件之外,并且当它出现时,边距需要不同。因此,如果孩子出现在其中,我希望让父母更改它们。
  • 我认为在这种情况下,在父组件周围有一个容器应该可以帮助您应用边距。
猜你喜欢
  • 2016-06-10
  • 2010-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多