【问题标题】:Why does ':last-child' change the priority of styles?为什么 ':last-child' 会改变样式的优先级?
【发布时间】:2014-04-07 08:13:29
【问题描述】:

我遇到了一个让我感到困惑的场景 - :last-child 的使用会影响父类的应用方式。

我有一个元素列表,目标是对最后一个元素应用一些样式。

但是,当我使用:last-child 时,样式的优先级发生了变化,并且其中一个父类停止工作,只有!important 解决了这个问题。

我在这里做了一个简单的演示: http://jsfiddle.net/wC2AX/1/

HTML:

<div class="hover">
    <div class="focus_on_last_child" style="background-color:red; width:100px;  height:100px">
        <div class="attribution">

        </div>
    </div>
</div>

CSS:

/*this should be applied on hover always*/
.hover:hover .attribution{
        background-color: black; /*try adding !important*/
        bottom: 0px;

}

/*basic properties*/
.attribution {
    height: 60px;
    overflow: hidden;
    position: absolute;
    bottom: -60px;
    width: 100px;
}

/*depending on a screen size styles are changed*/
.focus_on_last_child:last-child .attribution { /*try removing :last:child*/
    background-color: pink;
    bottom: -30px;
}

这个例子有点愚蠢,应该改变悬停样式的想法。但它仅在使用!important 或删除:last-child 时才有效。

感谢您的任何建议!

【问题讨论】:

    标签: html css


    【解决方案1】:

    这是选择器specificity的问题。

    您的第一条规则有两个类和一个伪类:

    .hover:hover .attribution
    

    你的最后一条规则也有两个类和一个伪类(:last-child 就是那个伪类):

    .focus_on_last_child:last-child .attribution
    

    由于您的两条规则同样具体,因此后面的规则将具有优先权。当您删除 :last-child 伪类时,仅保留两个类选择器,因此该规则的特异性会降低,从而允许您的 :hover 规则优先。

    最简单的解决方案是将:hover 规则移到:last-child 规则下面,这样该规则就具有优先权,您就不必使用!important

    【讨论】:

    • 我也注意到了。但是当我读到你已经回答的问题时......
    • 击败我,如果 html 如上所述,我也不认为@Anelook 实际上需要最后一个子选择器
    • 我认为没有必要在:last-child 下添加:hover。你根本不需要:last-child,请see my answer
    • 我不想对 OP 的实际代码 @Pete 和 rednaw 做太多假设,这就是我将 :last-child 留在那里的原因。
    【解决方案2】:

    因为:

    .hover:hover .attribution{
    

    比以下更具体:

    .focus_on_last_child .attribution {
    

    但如果您将.hover 添加到它,它会更具体,并且会起作用:

    .hover .focus_on_last_child .attribution {
    

    【讨论】:

      猜你喜欢
      • 2020-05-24
      • 1970-01-01
      • 1970-01-01
      • 2021-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多