zl程序教程

您现在的位置是:首页 >  工具

当前栏目

【CSS笔记】CSS选择器的优先级(权重)

笔记CSS 选择器 优先级 权重
2023-09-14 09:13:55 时间

目录

1.1、选择器的优先级

1.2、CSS选择器权重


1.1、选择器的优先级

CSS选择器的优先级顺序如下所示:

内联样式(style) > id选择器 > class选择器 > 元素选择器 > 通用选择器。

在CSS里面,如果有多个选择器作用在同一个元素上面,那么会按照上面的优先级顺序进行样式的选取,也就是优先级越高,浏览器最终就显示哪种样式。

<!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.0">
    <title>CSS选择器</title>
    <style>
        * {
            color: blue; 
            font-size:30px;
        }
        div {
            color: green;
            font-size:30px;
        }
        #box {
            color: yellow; 
            font-size:30px;
        }
        .box {
            color: skyblue; 
            font-size:30px;
        }
    </style>
</head>
<body>
    <div style="color: red; font-size:30px;" id="box" class="box">
        CSS选择器
    </div>
    <div id="box" class="box">
        CSS选择器
    </div>
</body>
</html>

1.2、CSS选择器权重

对于哪些组合选择器,我们可以通过计算选择器的权重来查看优先级,权重越大,优先级越高。

通过上面五个选择器的权重值,就可以计算出任意组合的权重值了,权重值就是将所有的权重相加。

<!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.0">
    <title>CSS选择器</title>
    <style>
        /* 权重值:0 */
        * {
            color: blue;
            font-size: 30px;
        }

        /* 权重值:1 */
        div {
            color: green;
            font-size: 30px;
        }

        /* 权重值:1 + 1 = 2 */
        div p {
            color: greenyellow;
        }

        /* 权重值:100 */
        #box {
            color: yellow;
            font-size: 30px;
        }

        /* 权重值:100 + 1 = 101 */
        #box p {
            color: lightcoral;
            font-size: 40px;
        }

        /* 权重值:1 + 100 + 1 = 102 */
        div#box p {
            color: lightseagreen;
            font-size: 50px;
        }

        /* 权重值:10 */
        .box {
            color: skyblue;
            font-size: 30px;
        }

        /* 权重值:10 + 1 = 11 */
        .box p {
            color: skyblue;
            font-size: 30px;
        }
    </style>
</head>

<body>
    <div>
        <div id="box" class="box">
            <p>
                CSS选择器
            </p>
        </div>
    </div>
</body>

</html>

以上,就是CSS选择器的优先级(权重)。