问答

关于hover优先级问题

作者:admin 2021-05-06 我要评论

style .box { width: 200px; height: 200px; background-color: green; } .box .center { width: 150px; height: 150px; background-color: blueviolet; } .flex...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)
<style>
        .box {
            width: 200px;
            height: 200px;
            background-color: green;
        }

        .box .center {
            width: 150px;
            height: 150px;
            background-color: blueviolet;
        }
        .flex {
            display: flex;
            justify-content: center;
            align-items: center;
        }
        /* 30 */
        .box .center .inner {
            width: 100px;
            height: 100px;
            background-color: green;
        }
        /* 10+10 */
        .box:hover .inner {
            background-color: red;
        }
    </style>
    
    <div class="box flex">
        <div class="center flex">
            <div class="inner"></div>
        </div>
    </div>

如上代码为什么hover有效果是红色,不是应该绿色不变吗,从优先级来看的也是绿色才对吧

###

一个选择器的优先级可以说是由四个部分相加?(分量),可以认为是个十百千 —?四位数的四个位数:

  1. 千位:?如果声明在 [style](https://developer.mozilla.org/zh-CN/docs/Web/HTML/Global_attributes#attr-style)?的属性(内联样式)则该位得一分。这样的声明没有选择器,所以它得分总是1000。
  2. 百位:?选择器中包含ID选择器则该位得一分。
  3. 十位:?选择器中包含类选择器、属性选择器或者伪类则该位得一分。
  4. 个位:选择器中包含元素、伪元素选择器则该位得一分。

因此我们可以知道

/* 0030 */
.box .center .inner {
    width: 100px;
    height: 100px;
    background-color: green;
}
/* 0030 */
.box:hover .inner {
    background-color: red;
}

两者优先级相同,根据位置确定关系,因此有红色。

ps: 在进行计算时不允许进行进位,例如,20 个类选择器仅仅意味着 20 个十位,而不能视为 两个百位,也就是说,无论多少个类选择器的权重叠加,都不会超过一个 ID 选择器。
###

:hover属于伪类,从优先级来说,比类选择器高多了

###

优先级:
0 important
1 行内元素
2 id
3 类和伪类
4 元素和伪元素

如优先级相同时,根据位置顺序确定优先关系

###

伪类的权重>类名

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • 关于hover优先级问题

    关于hover优先级问题

  • mongodb查询缓慢

    mongodb查询缓慢

  • 手机app内部打开了h5(h5是个在线客服

    手机app内部打开了h5(h5是个在线客服

  • 前端怎么和app对接拿到token

    前端怎么和app对接拿到token

腾讯云代理商
海外云服务器