前端 CSS层叠性 CSS选择器优先级

层叠性

层叠性:权重的标签覆盖掉了权重小的标签,说白了 ,就是被干掉了

权重:谁的权重大,浏览器就会显示谁的属性

我们现在已经学过了很多的选择器,也就是说在一个HTML页面中有很多种方式找到一个元素并且为其设置样式,那么就会有一个问题:如果我通过不同的选择器找到了相同的一个元素,并且设置了不同的样式,那么浏览器究竟应该按照哪一个样式渲染呢?也就是不同的选择器它们的优先级是怎样的呢?

其实是按照不同选择器的权重来决定的,具体的选择器权重计算方式如下图:

类选择器权重大于标签选择器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
    <style>
        p{
            color: red;
            font-size: 30px;
        }

        .spe1{
            color: yellow;
            font-size: 40px;
        }
        

    </style>
</head>
<body>
    <div>
        <p class="spe1">我是什么颜色</p>
        <p class="spe1">我是什么颜色</p>
    </div>
</body>
</html>

 当权重一样的时候 是以后来设置的属性为准,前提必须权重一样 。‘后来者居上 ’

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
    <style>

        .spe1{
            color: yellow;
            font-size: 40px;
        }

        .spe2{
            color: green;
            font-size: 40px;
        }

    </style>
</head>
<body>
    <div>
        <p class="spe1 spe2">我是什么颜色</p>
        <p class="spe1 spe2">我是什么颜色</p>
    </div>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/mingerlcm/p/10803628.html
今日推荐