【HTML+CSS】选择器权重

参会人:@鹿维恩
会议时间:2022-11-17
会议地点:3号会议室

选择器权重

内联样式表 1000
id选择器 100
class选择器 10
标签选择器 1
通配符 0

<style>
    div{
        background-color: black;
    }
    #box{
        background-color: green;
    }
    .tom{
        background-color: yellow;
    } 
</style>
		<!-- 内联 class id权重比较 -->
    <div style="background-color: red;" id="box" class="tom">文字</div>
    <div id="box" class="tom">文字</div>

后代子代权重 相加
群组选择器 看自身
伪类选择器 10
继承样式 0

<style>
    .son{/* 权重=10 */
        background-color: antiquewhite;
    }
    .father div{/* 权重=10+1 */
        background-color: aquamarine;
    }
    .father .son{/* 权重=10+10 */
        background-color: skyblue;
    }
    #tom{/* 权重=100 */
        background-color: lightcoral;
    }
    .father #tom{/* 权重=10+100 */
        background-color: blue;
    }
    body .father #tom{/* 权重=1+10+100 */
        background-color: red;
    }
</style>
<div class="father">
        <!-- 内联样式权重=1000 -->
        <div class="son" id="tom" style="background-color: green;">背景颜色改变</div>
</div>

!important 权重10000

这个是css提供的。用法:直接加在属性的后面,提高当前属性的权重
一个属性只能加一个!important
不建议加给内联样式(强强联合)

<style>
        .son{
            width: 200px;
            height: 200px;
            background-color: yellow !important;
        }
        .father .son{
            width: 300px;
            height: 300px;
            background-color: pink;
        }
</style>
<div class="father">
        <div class="son">son</div>
</div>

三大特征

继承、层叠、优先级

  • 继承
    • 继承的权重是0
    • 子元素可以继承父元素的部分属性
      • 文本属性
      • 列表属性
      • 表格属性
  • 层叠
    • 一个标签可以被多个选择器选中,不同的属性叠加作用
  • 优先级
    • 一个标签可以被多个选择器选中,相同属性看权重
<style>
    .father{
        width: 300px;
        height: 300px;
        background-color: pink;
        /* 继承 */
        color: blue;
    }
    .son{
        background-color: yellow;
    }
    .father .son{
        font-size: 40px;
    }
    /* 优先级 */
    .father div{
        background-color: green;
    }
</style>
<div class="father">
        <div class="son">son</div>
</div>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

芒果Cake

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值