【问题标题】:CSS : Inheritance is not working as exected in subclassesCSS:继承在子类中无法正常工作
【发布时间】:2015-10-26 00:11:34
【问题描述】:

我有一个 CSS 类“MyParent”,它被多个子类继承。 我想要“MyParent”类的一些属性,应该被子类覆盖,并且这个覆盖不应该影响其他子类。 请查找以下示例。

.MyParent {
  border-style: solid;
  border-color: red;
  background-color: yellow;
  color: red;
}
.MyChild1 .MyParent{
   background-color: blue !important;
   color: white !important;
}

.MyChild2 .MyParent{
  background-color: yellow !important;
  color: black !important;
}

我的 Html 如下所示。

<div class="MyParent">
 this is parent div
</div>

<div class="MyChild1">
 this is child1
</div>

<div class="MyChild2">
 this is child2
</div>

我希望 MyParent div 以黄色背景颜色显示,字体颜色为红色,这工作正常,但尽管我覆盖了属性,但其余 div 没有按预期工作。我所做的是,请在下面找到代码。

.MyChild1, .MyParent{
  background-color: blue !important;
  color: white !important;
 }

.MyChild2, .MyParent{
   background-color: green !important;
   color: white !important;
}

现在它部分工作,但我们在类“MyChild2”中覆盖的属性正在影响父类属性。因此,具有“MyParent”类的 div 由于这种继承而没有按预期进行渲染。因此,在应用程序的大多数地方,输出都受到干扰。如果我想让它按预期工作,我可以再写一个子类,我们可以做到,而且每次都写子类也很烦人一些属性,如边框颜色没有被继承 .但是为什么在 CSS 中会出现这种行为,以及我们如何纠正它。谁能给我解释一下。

提前致谢, 萨兰。

【问题讨论】:

    标签: css css-float


    【解决方案1】:

    CSS 属性仅在其值设置为 inherit 时从父元素继承。

    许多属性,例如color,都将inherit 作为默认值,因此它们无需任何进一步操作即可继承。

    大多数布局属性,包括边框,都有不同的默认值(通常是0),所以它们不会从父元素继承,除非你手动将它们设置为inherit。毕竟,如果你给一个元素加了一个边框,你不希望它里面的每个元素都得到一个相似的边框……

    要查看任何给定属性的默认值,请查看 MDN。

    【讨论】:

    • 这并不完全正确。有些属性是继承的,有些不是。被继承的初始值不是inherit,而是在级联没有产生值时继承。继承的和非继承的都可以通过inherit 强制继承。见w3.org/TR/css-cascade-4/#inheriting
    【解决方案2】:

    在 CSS 中,您不能让规则集从其他规则集继承样式。

    Inheritance 只能从父母传给孩子:

    继承 将属性值从父元素传播到其子元素。元素上属性的继承值是 元素父级属性的computed value 元素。

    相反,我认为您对cascading 感兴趣:

    级联采用declared values的无序列表作为 给定元素上的给定属性,按它们的声明对它们进行排序 如下确定的优先级,并输出单个 cascaded value

    .MyParent, .MyChild1, .MyChild2 {
      border-style: solid;
      border-color: red;
      background-color: yellow;
      color: red;
    }
    .MyChild1 {
       background-color: blue;
       color: white;
    }
    .MyChild2 {
      background-color: yellow;
      color: black;
    }
    <div class="MyParent">
     this is parent div
    </div>
    <div class="MyChild1">
     this is child1
    </div>
    <div class="MyChild2">
     this is child2
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2014-12-27
      • 2013-11-02
      • 1970-01-01
      相关资源
      最近更新 更多