CSS选择器级联/特异性无法按预期工作

时间:2015-01-06 18:12:42

标签: css css-selectors css-specificity

详细

我正在使用FirefoxDeveloperEdition并遇到意外的选择器优先级。我已经阅读了Smashing Magazine article "CSS Specificity: Things You Should Know",并且就我所知,已经构建了CSS选择器,因为它们应该是为了达到每个选择器的预期特异性水平。但是,错误的声明正在被取消。

问题是什么,在这里?我是不是完全围绕选择器特异性的运作?这是一个错误吗?或者,别的什么?

项目代码(简化)

/index.html

<head>
  <link href="css/style.css">
</head>
<body>
  <section class="hud">
    <section class="main float-l">
      <a href="#0" class="button">
        <div class="outer container">
          <div class="inner container">
            <p class="show"> <!-- This text is meant to be white by the style declared at line 159. But, it's grey by line 61. -->
              View Details
            </p>
            <div class="arrow"></div>
            <p class="hide"> <!-- This text is meant to be white by the style declared at line 159. But, it's grey by line 61. -->
              Hide Details
            </p>
          </div>
        </div>
      </a>
    </section>
  </section>
</body>

/css/style.css

58  .hud > .main p /* I also tried `.hud > .main p:not(.button)` */
59    {
60      vertical-align:   middle;
61      color:            #7C7C7C; /* This grey is applied of the white of line 159. */
62    {

...

155 .hud > .main > .button
156   {
157     display:          block;
158     background-color: #986B99;
159     color:            #FFFFFF; /* This white should be applied, but is overridden by the grey of line 61. */
160     height:           36px;
161     margin:           20px 10px 10px;
162     padding:          8px 20px;
163     font-weight:      400;
164     text-decoration:  none;
165     text-transform:   uppercase;
166     border-radius:    2px;
167   }

检查

尝试.hud > .main > .button vs .hud > .main p
Firefox dev tools inspector showing overridden CSS

还尝试了.hud > .main > .button vs .hud > .main p:not(.botton)
Firefox dev tools inspector showing overridden CSS

1 个答案:

答案 0 :(得分:5)

这是因为第一个样式与元素匹配,第二个样式从它的父元素继承。

当两个选择器匹配相同的元素时,特异性仅起作用。不是从父元素继承样式。

你可以看到非常简单的例子:

#myID {
  color: red;
}

p {
  color: green;  
}
<div id="myId">
  <p>Some text</p>
</div>

即使#myId更具体,文字也是绿色的,因为p选择器直接匹配该元素,因此比color继承的div更重要。

要使p内的.button元素变为白色,您需要:

.hud > .main > .button p {
    color: #fff;
}