CSS-优先级与继承

    科技2022-08-03  112

    学习目标

    掌握选择器权重的判断方法

    CSS(cascade style sheet)层叠样式表

    一个元素的最终样式是由多个来源叠加后的结果

    一、样式来源

    使用不同的选择器设置的样式浏览器默认样式 (user agent stylesheet)继承的样式 (Inherited from xxx)

    二、优先级顺序

    !important > 内联样式(标签上得style上的属性) > 选择器设置样式 (css文件,style标签)> 浏览器默认样式 > 继承样式

    2.1、!important

    <div class="box"> <p>饥人谷</p> </div> <style> p { color: red!important; } .box p { color: blue; } </style

    •!important的优先级最高

    尽量少用!important,除非迫不得已 • 比如队友写了垃圾代码如内联样式,需要覆盖掉 • 比如有一些高优先级的代码,只能通过!important来覆盖

    2.2、浏览器默认样式

    <h1 style=”color: red;”>饥人谷</h1> <style> .body { color: blue; } h1 { color: green; } </style>

    第一个是内联样式 第二个是设置样式 第三个是默认样式 第四个是继承样式

    2.3、继承样式

    • 对于如下代码,a链接的样式是什么

    <div class="box"> <a href=”#”>饥人谷</a> </div> <style> .box { color: blue!important; } </style>

    a得样式是默认得颜色

    2.3.1、继承属性与非继承属性

    • 继承属性(和文本相关的大多数可继承)

    color、 font-size、font-family、line-height • 非继承属性border、background、margin、padding、display… • 如何查询该属性是否可继承在下面的链接里可查看是否继承https://www.w3.org/TR/CSS21/propidx.html
    2.3.2、控制继承

    • inherit

    使用继承自父级的样式

    • initial

    使用该属性的initial value(该默认值不是前面讲过的浏 览器默认值 user agent stylesheet)https://www.w3.org/TR/CSS21/propidx.html 查看属性initial value

    • unset

    如果是继承属性则继承父级,如果是非继承属性就用initial value

    • 两个案例,解释现象原因

    <body style="color: red"> <em style="color: inherit">这是红色,为什么?</em> 继承颜色 红色 <em style="color: initial">这是黑色,为什么?</em> 默认得颜色 黑色 <em style="color: unset"> 这也是红色,为什么 </em> 如果是继承得就 继承颜色,如不是 就默认元素得初始颜色 红色 </body> <body style="font-size: 18px"> <h1 style="font-size: inherit">18px,为什么 </h1> <h1 style="font-size: initial">16px, 为什么</h1> <h1 style="font-size: unset"> 18px,为什么 </h1> </body>

    设置的样式 不同属性会叠加、相同属性会覆盖

    • 选择器优先级不同

    优先级高的会覆盖优先级低的

    • 选择器优先级相同

    后面的会覆盖前面的

    三、优先级计算

    • 计算方法 千位: 如果声明在 style 的属性(内联样式)则该位得一分 百位: 选择器中包含ID选择器则该位得一分 十位: 选择器中包含类选择器、属性选择器或者伪类则该位得一分。 个位:选择器中包含元素、伪元素选择器则该位得一分。 通用选择器 (*),组合符 (+, >, ~, ’ '),和否定伪类 (:not) 不会影响优先级

    案例1 • 设置的样式权重大于继承样式

    <p id=“detail” class=”box”> <span class=”active”>这hello 饥人谷</span> </p> <style> #detail { color: red; } span { color: blue} </style>

    案例2 • 权重相同,看位置

    <p id=“detail” class=”box”> <span class=”active”>这hello 饥人谷</span> </p> <style> .box span { color: red; } p .active { color: blue} </style>

    • 权重不同,数位数

    <p id=“detail” class=”box”> <a class=”goto” href=”https://jirengu.com”>饥人谷</a> </p> <style> #detail a { /*0101*/ color: red; } #detail.box > a.goto { /*0121*/ color: blue; } .box a:hover { /*0021*/ color: yellow; } #detail a.goto[href^=”https://jirengu.com”]::before { /*0122*/ content: '� ' ; } </style>

    参考

    https://developer.mozilla.org/zh- CN/docs/Learn/CSS/Building_blocks/Cascade_and_in heritance

    对于设置的样式,计算选择器权重。 如果权重相同,位置靠下的覆盖位置靠上的。如果权重不同,权重高的覆盖权重低的。

    权重的计算:内联 千位;id百位;class、属性、伪类 十位;标签、伪元素个位。> 、~、+、:not 不计入

    Processed: 0.020, SQL: 8