CSS 继承性和优先级

继承性和优先级

CSS继承性

CSS属性继承:外层元素的样式,会被内层元素进行继承。多个外层元素的样式,最终都会“叠加”到内层元素上。

实例:

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>php.cn</title>
    <style type="text/css">
     div{
         color:red;
     }
     h1{
        color:blue; 
     }
     p{
         color:green;
     }
    </style>
    </head>
    <body>
        <div>
        <h1>主席心中的互联网</h1>
        <p>互联网是20世纪最伟大的发明,它正在将人类“一网打尽”,人们在不知不觉中已经融入了互联网生态,互联网让世界变成了“鸡犬之声相闻”的地球村。
        </p>
        </div>
    </body>
</html>

在本地查看 f12 可以看到

25.png

什么样的CSS属性能被继承呢?

CSS文本属性都会被继承的:

color、 font-size、font-family、font-style、 font-weight

text-align、text-decoration、text-indent、letter-spacing、line-height

提示:<body>中的CSS属性,会被所有的子元素继承。

CSS优先级

单个选择器的优先级

行内样式 > id选择器 > class选择器 > 标签选择器

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>php.cn</title>
    <style type="text/css">
     h1{
         color:green;
     }
    .hclass{
        color:bule;
    }
    #hid{
        color:black;
    }
    </style>
    </head>
    <body>
        <div>
        <h1 class="hclass" id="hid"  style="color:red">主席心中的互联网</h1>
        </div>
    </body>
</html>

利用 f12 观察:

26.png

多个选择器的优先级

多个选择器的优先级,一般情况下,指向越准确,优先级越高。

特殊情况下,我们需要假设一些值:

  • 标签选择器 优先级为1
  • 类选择器 优先级为10
  • Id选择器 优先级为100
  • 行内样式 优先级为1000

计算以下优先级

.news h1{color:red;} 优先级:10 + 1 = 11

.title{color:blue;} 优先级:10

div.news h1{color:red;} 优先级:1 + 10 + 1 = 12

h1.title{color:blue;} 优先级:1 + 10 = 11

posted @ 2022-07-07 15:07  ppqppl  阅读(37)  评论(0编辑  收藏  举报