html - CSS 中继承和特殊性的混淆

标签 html css inheritance

以下是我正在努力了解 CSS 中这两个规则之间差异的 html 文件。

<!DOCTYPE HTML>
<html>

<head>
  <meta charset="UTF-8">
  <title>specificity</title>
  <!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
  <style>
    aside,
    article,
    section,
    header,
    footer,
    nav {
      display: block;
    }
    body {
      font-family: Georgia;
      font-size: 120%;
    }
    /*add styles here*/
    #mainContent p {
      color: red;
    }
    p {
      color: blue;
    }
    .green {
      color: green;
    }
    /**/
  </style>
</head>

<body>
  <section id="mainContent">
    <p>I am a paragraph nested inside a section. I also have a <strong class="green">strong tag</strong> nested inside of me.</p>
  </section>
</body>

</html>

下面是我不太清楚的声明:

Specificity works just fine until inheritance is involved. If a child element has a style that differs or conflicts with the parent styles, the child styles always win. So for strong element above, we are seeing inheritance and not specificity.

但如果我申请green类别为 <p>元素,我正在观察特殊性,因为样式绿色被忽略并且带有 id 的样式应用于段落。

我的问题是,因为 <p><section> 的 child 根据上面的陈述,这里不应该观察到继承,就像观察到 <strong> 一样元素?

最佳答案

每个 CSS 规则仅适用于其选择器的主题

对于 p { ... } 主题全是p元素

对于 #mainContent p { ... } 主题全是p id 为 mainContent 的元素内的元素.

如果 p元素位于 ID 为 mainContent 的元素内, #mainContent p { ... }规则获胜,因为它是一个更具体的规则。

strong元素不是任一规则的主题,因此两者均不直接应用。

在示例中,strong 元素是 .green { ... } 的主题规则。这就是适用于该元素的规则。

那么继承从何而来?

元素的属性继承可以通过以下两种方式之一进行。

首先,可以有一个显式规则,其subject 是元素,属性设置是inherit。 .所以strong { color:inherit; }如果它是 strong 的级联中具有颜色属性的最高优先级规则,将会元素,强制该元素的颜色取自其父元素的颜色。

或者,如果给定 strong 的级联中的任何地方都没有规则元素定义了一个特定的属性,该元素将采用默认值。一些属性被定义为“继承的”,而另一些则不是。 color属性(property)被定义为继承。

因此,在这种替代情况下,只有当没有规则的 subject 是给定元素并且具有 color 时属性,给定元素的颜色是否继承自包含元素的颜色。

在你的例子中。有多个规则,其中 p 元素是主题并且定义了 color 元素,因此没有继承对此有效。

关于html - CSS 中继承和特殊性的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37361205/

相关文章:

javascript - Fancytree - 将新元素添加到树节点(日期、注释等)

inheritance - Swagger 2.0 中的抽象父类

c++ - 在派生类中使用基构造函数的任何方法?

php - 页面加载时的模态显示

javascript - 两行文本和溢出是虚线

继承类上的 PHP new self() 正在创建基类对象

javascript - 单击按钮的 Chrome 扩展程序

Javascript - 单击事件在 "infinite scroll"之后不再起作用

html - 将滚动条添加到模态窗口

html - 绝对定位的 div 包含一个 overflow hidden 的子 div,其中包含 2 个 div,一个固定高度和一个滚动