什么是继承性?
作用: 给父元素设置一些属性, 子元素也可以使用, 这个我们就称之为继承性
示例代码:
<style> div{ color: red; } </style> <div> <ul> <li> <p>我是段落</p> </li> </ul> </div> <!--p会变成红色-->
<style> div{ color: red; text-decoration: none; font-size: 30px; } </style> <div> <a href="#">我是超链接</a> </div> <div> <h1>我是大标题</h1> </div> <!--a的颜色和下划线不会发生变化, H的字体大小不对 -->
body{ font-size: 30px; font-family: "微软雅黑" color: #666; }
CSS全称 Cascading StyleSheet (层叠式样式表), 其中的层叠就是指层叠性
什么是层叠性?
作用: 层叠性就是CSS处理冲突的一种能力
示例代码
<style> p{ color: red; } .para{ color: blue; } </style> <p id="identity" class="para">我是段落</p> <!-- 最终显示蓝色, 因为红色被覆盖掉了 -->
什么是优先级?
作用:当多个选择器选中同一个标签, 并且给同一个标签设置相同的属性时, 如何层叠就由优先级来确定
优先级判断的三种方式
间接选中就是指继承
如果是间接选中, 那么就是谁离目标标签比较近就听谁的
<style> li{ color: blue; } ul{ color: red; } </style> <ul> <li> <p id="identity" class="para">我是段落</p> </li> </ul> <!-- 最终显示蓝色 -->
<style> p{ color: blue; } p{ color: red; } </style> <ul> <li> <p id="identity" class="para">我是段落</p> </li> </ul> <!-- 最终显示红色 -->
<style> #identity{ color: purple; } .para{ color: pink; } p{ color: green; } *{ color: blue; } li{ color: red; } </style> <ul> <li> <p id="identity" class="para">我是段落</p> </li> </ul> <!-- 最终显示紫色 -->
什么是优先级的权重?
作用: 当多个选择器混合在一起使用时, 我们可以通过计算权重来判断谁的优先级最高
权重的计算规则
首先先计算选择器中有多少个id, id多的选择器优先级最高
如果id的个数一样, 那么再看类名的个数, 类名个数多的优先级最高
如果类名的个数一样, 那么再看标签名称的个数, 标签名称个数多的优先级最高
如果id个数一样, 类名个数也一样, 标签名称个数也一样, 那么就不会继续往下计算了, 那么此时谁写在后面听谁的
示例代码
<style> #identity1 .box2{ color: red; } .box1 .box2{ color: green; } div ul li p{ color: blue; } </style> <div id="identity1" class="box1"> <ul> <li> <p id="identity2" class="box2">我是段落</p> </li> </ul> </div> <!-- id多最终显示红色 -->
<style> .box1 .box2{ color: blue; } div .box2{ color: green; } </style> <div id="identity1" class="box1"> <ul> <li> <p id="identity2" class="box2">我是段落</p> </li> </ul> </div> <!-- id一样, 比类多, 最终显示蓝色 -->
<style> #identity1 ul li p{ color: red; } #identity1 ul p{ color: green; } </style> <div id="identity1" class="box1"> <ul> <li> <p id="identity2" class="box2">我是段落</p> </li> </ul> </div> <!-- id一样, 类一样, 比标签多最终显示红色 -->
<style> .box1 li #identity2{ color: blue; } #identity1 ul .box2{ color: red; } </style> <div id="identity1" class="box1"> <ul> <li> <p id="identity2" class="box2">我是段落</p> </li> </ul> </div> <!-- id一样, 类一样, 标签一样, 最终显示红色 -->
什么是!important
作用: 用于提升某个直接选中标签的选择器中的某个属性的优先级的, 可以将被指定的属性的优先级提升为最高
示例代码
<style> #identity{ color: purple; font-size: 50px; } .para{ color: pink ; } p{ color: green !important; } </style> <ul> <li> <p id="identity" class="para">我是段落</p> </li> </ul> <!-- 最终显示绿色 -->