CSS权重,你真的懂了么

1.什么是CSS权重?

css权重决定了哪个css规则会起重要,当多个规则被应用于同一个元素时,权重高的将会起作用(权重高代表优先级高)。在日常开发过程中,大家多少都遇到过这样的问题,写不同的css样式文件,结果产生相互覆盖的问题。本文将详细讲述一下css权重规则,便于大家避坑。

2.CSS权重规则(级别由高到低)

(1) !important 声明级别最高,但同时也会被important级别覆盖。
例子如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    body{
        background-color: pink;
    }
    .headText{
        color: red !important;
        margin: 0 auto;
        text-align: center;
    }
    .headText{
        color: blue;
    }
</style>
<body>
<div>
    <h1 class="headText">HELLO WORLD</h1>
</div>
</body>
</html>

页面呈现的样式结果:
在这里插入图片描述
上面对h1的class的样式定义了两次,字体颜色分别声明为red和blue,然而显示的却是红色,是因为!important增加了该样式的权重。如果在blue后再添加!important,则会显示蓝色,后一个important属性覆盖了前一个。

(2)行内样式会覆盖行外任何样式,除了!important

<style>
    body{
        background-color: pink;
    }
    .headText{
        color: red;
        margin: 0 auto;
        text-align: center;
    }
</style>
<body>
<div>
    <h1 class="headText" style="color: #000;">HELLO WORLD</h1>
</div>

显示结果:
在这里插入图片描述
上述代码中,在h1的行内定义了属性:style=“color: #000;”,同时在外部,对类也定义了字体的color属性,然而显示的却是在行内定义的黑色。是因为行内样式的权重较高,会覆盖任何行外样式,但若行外加上!important,则不会被覆盖。

(3)ID选择器,权重100

<style>
    body{
        background-color: pink;
    }
    .headText{
        color: red;
        margin: 0 auto;
        text-align: center;
    }
    #headText{
        color: blue;
    }
</style>
<body>
<div>
    <h1 class="headText" id="headText">HELLO WORLD</h1>
</div>

在同时定义了类属性的css和id样式属性,效果如下:
在这里插入图片描述
起作用的id样式属性,如果在行内添加属性,则行内属性高于id样式属性。

(4)class类,属性选择器和伪类选择器,权重10
这一类包括各种class,属性选择器,伪类选择器比如 :hover,:focus等等。

a:hover{
        color: blue;
       }
</style>
<body>
<div>
    <a id="alink" class="alink">点我</a>
<div>

伪类选择器给类添加了一个样式属性,显示效果如下:
在这里插入图片描述
(5)标签选择器和伪元素选择器,权重1
伪元素包含::after,:before,:first-letter,:first-line,:selecton

<style>
    body{
        background-color: pink;
    }
    p:first-letter{
        color:#ff0000;
        font-size:xx-large;
    }
</style>
<body>
<div>
    <p>这是一个小栗子</p>
    <p>这是程小白写的一个小栗子</p>
    <p>这是另一个小栗子</p>
</div>

案例如下:
在这里插入图片描述

3.总结

样式等级关系如下图:

 !important > 行内样式 > ID选择器 > 类选择器 (属性选择器 | 伪类选择器) > 元素选择器

具体细则:

(1)!important是优先级最高的,但同时也会被更高权重的important覆盖掉。
(2)行内样式高于行外任何样式(除了 !important)。
(3)css权重不能够跨越等级,以类属性为例,n个类属性相加也不能超越一个id属性,同级别相互比较有效。
(4)权重不同的选择器作用于同一个选择器,最高的权重的那个css产生作用;(5)权重相同的,后出现的选择器会覆盖前面的,后面的产生作用。

猜你喜欢

转载自blog.csdn.net/qq_33479841/article/details/103047627