CSS

选择器的优先级

suaxi
2024-03-05 / 0 评论 / 20 阅读 / 正在检测是否收录...
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>选择器优先级</title>
    <style>
        /* 行内 > id选择器 > 类选择器 > 元素选择器 > 通配选择器 */
        #sunxiaochuan {
            color: blue;
        }

        .slogan {
            color: yellow;
        }

        h2 {
            color: red;
        }
        * {
            color: green;
        }
    </style>
</head>
<body>
    <h2 id="sunxiaochuan" class="slogan" style="color: blueviolet;">孙笑川</h2>
</body>
</html>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>选择器优先级</title>
    <style>
        /* 权重计算:(a,b,c) */
        /* 
        a:ID选择器的个数
        b:类、伪类、属性 选择器的个数
        c:元素、伪元素 选择器的个数
        
        注:行内样式权重大于所有选择器
        !important 的权重大于行内样式,大于所有选择器,权重最高
        */

        #test {
            color: purple;
        }

        /* (1,0,0) */
        #jialidun {
            color: orange;
        }

        /* (0,2,1) 从左到右依次比较大小,当前位胜出后,后面的不再对比 */
        .container span.slogan {
            color: red;
        }

        /* (0,1,3) */
        div>p>span:nth-child(1) {
            color: green;
        }

        .slogan {
            color: blue !important;
        }
    </style>
</head>
<body>
    <div class="container" id="test">
        <p>
            <span id="jialidun" class="slogan">家里蹲大学</span>
            <span>欢迎新同学</span>
        </p>
    </div>
</body>
</html>
0

评论 (0)

取消