【问题标题】:CSS selector cascading/specificity not working as expectedCSS选择器级联/特异性未按预期工作
【发布时间】:2015-03-04 11:16:52
【问题描述】:

详情

我在 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 &gt; .main &gt; .button vs .hud &gt; .main p

也试过.hud &gt; .main &gt; .button vs .hud &gt; .main p:not(.botton)

【问题讨论】:

  • 您的预期结果是什么,您的实际结果是什么?你还没有告诉我们那个关键的部分。此外,一个 JSFiddle 示例会很有帮助。
  • 好吧,按钮是a,而不是p
  • @TylerH 正如 CSS 代码块的 cmets 中所述,我希望 .button 内的 p 元素具有白色文本。
  • 在未来,你应该把你的预期结果放在纯文本中,而不是把它们埋在代码 cmets 中。我想知道我在寻找什么在查看代码之前
  • @Chad 这和什么有什么关系?

标签: css css-selectors css-specificity


【解决方案1】:

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

只有当两个选择器匹配同一个元素时,特异性才会发挥作用。在从父元素继承样式时不是这样。

您可以在非常简单的示例中看到这一点:

#myID {
  color: red;
}

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

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

要在.button 中制作p 元素,您需要:

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

【讨论】:

  • 特异性不能通过继承发挥作用。啊,好吧!太好了,谢谢。
猜你喜欢
  • 2020-05-25
  • 2022-06-11
  • 1970-01-01
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
  • 2014-03-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多