初级前端的自我救赎【HTML+CSS篇】:6.选择器权重与样式权重

选择器权重 
1.相同选择器:根据书写顺序 后面的会覆盖前面的
2.不同选择器:ID(100)> CLASS(10)> element(1)
3.层级选择器:按权重累加计算
            
<!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>Document</title>
    <style>
        .myTitle {
            color: red;
            color: green;
            color: yellow;
        }

        .title {
            color: red;
        }

        #txt {
            color: blue;
        }

        h1 {
            color: black;
        }

        /* 层级选择器 */
        /* 10 + 100 = 110 */
        .box #text{
            color: red;
        }
        /* 100 + 1 = 101 */
        #box2 h2{
            color: green !important;
        }

        /* !important 设置最高权重 */
    </style>
</head>

<body>
    <h1 class="myTitle">相同选择器</h1>
    <h1 class="title" id="txt">hello world</h1>

    <div class="box" id="box2">
        <h2 id="text">层级选择器</h2>
    </div>
</body>
可以用!important来设置最高权重,一般工作中基本不会用id。
引用别人的代码或样式想修改但权重不够的话就用!important就可以了。
</html>

样式权重:
权重:内联样式高于嵌入样式高于外部样式
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.0">
    <title>Document</title>
    <!-- 外部样式(实际工作中大部分会用外部样式) -->
    <link rel="stylesheet" href="common.css">
    <!-- 嵌入样式 -->
    <style>
        h1{
            color: blue;
        }
    </style>

    <!-- 权重:内联高于嵌入高于外部样式 -->
</head>
<body>
    <!-- 内联样式,行内样式,权重要高于嵌入样式 -->
    <h1 style="color: red;">hello world</h1>
</body>
</html>

CSS代码:

h1{
    color: white;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值