CSS属性覆盖。为什么?

时间:2016-09-04 14:15:28

标签: html css html5 css-selectors

为什么h2选择器在这里受到尊重?我很确定它不应该。

h1,
h2,
h3 {
  color: #204466;
}
figure.portfolio-item > figcaption {
  color: #ffffff !important;
}
<figure class="portfolio-item">
  <figcaption>
    <h2>The title</h2>
    <p>
      The content.
    </p>
  </figcaption>
</figure>

2 个答案:

答案 0 :(得分:2)

如果你想覆盖h2样式,你应该像这样:

figure.portfolio-item > figcaption h2 {
  color: #333 !important;
}

样式将inherit,但h2优先于此。

&#13;
&#13;
h1,
h2,
h3 {
  color: #204466;
}
figure.portfolio-item > figcaption h2 {
  color: #333 !important;
}
&#13;
<figure class="portfolio-item">
  <figcaption>
    <h2>The title</h2>
    <p>
      The content.
    </p>
  </figcaption>
</figure>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

在您的第二个选择器中,您不能直接选择h2,因此请选择h2,以覆盖&#34;一般规则&#34;在h2

之前申请

&#13;
&#13;
body {
  background: lightgrey
}
h1,
h2,
h3 {
  color: #204466;
}
figure.portfolio-item > figcaption h2, figure.portfolio-item > figcaption p {
  color: #fff
}
&#13;
<figure class="portfolio-item">
  <figcaption>
    <h2>The title</h2>
    <p>
      The muthafucking content.
    </p>
  </figcaption>
</figure>
&#13;
&#13;
&#13;