CSDN话题挑战赛第2期
参赛话题:学习笔记
目录
1.继承性
特性:子元素有默认继承父元素样式的特点
作用:恰当的使用继承可以简化代码,降低CSS样式的复杂性
可以继承的常见属性:color、font-style、font-weight、font-size、font-family、text系列、line系列等。
总的来说就是控制文字的都能继承,而其他不能继承。
继承失效的情况:
- a标签本身具有color颜色属性,继承失效
- 标题h系列本身具有font-size字体大小属性,继承失效
案例演示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* 继承性 */
div{
/* 控制文字的都能继承,其他不能继承 */
color: red;
font-size: 20px;
height: 100px;
}
</style>
</head>
<body>
<div>
div
<span>span</span>
<a href="">超链接</a>
<h1>h1</h1>
</div>
</body>
</html>
上图中a标签不能继承红色,h1标签不能继承字体大小。
2.层叠性
CSS全名叫Cascading Style Sheet(层叠样式表),名字就说明了它所具有的属性---层叠性。
特性:
- 给同一个标签设置不同的属性,样式会层叠叠加,共同作用在标签上
- 给同一个标签设置相同的属性,样式会层叠覆盖,最终写在最后的样式才会生效
注意:当样式冲突时,只有当选择器优先级相同,才能通过层叠性判断结果。
如:
div{
color: red;
color: blue;
}
此时div中的文字会显示蓝色而不是两者都有。
3.优先级
优先级特性是一个比较重要的特性。
基本概念
特性:不同选择器具有不同优先级,优先级高的选择器样式会覆盖优先级低的选择器样式。
优先级公式:
- 继承<通配符选择器<标签选择器<类选择器<id选择器<行内样式<!important
!important注意点:
1.!important写在属性值后面,分号的前面。
2.!important不能提升继承的优先级,只要是继承,优先级必然最低。
3.实际开发不推荐使用!important。
案例演示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* 继承 */
body{
color: red;
}
/* 标签选择器 */
div{
color: green !important;
}
/* 类选择器 */
.box{
color: blue;
}
/* 类选择器 */
#box{
color:orange ;
}
</style>
</head>
<body>
<!-- 行内样式 -->
<div class="box" id="box" style="color:pink">div</div>
</body>
</html>
最终显示的是绿色,优先级最高。
权重叠加计算
我们知道选择器可以复合,那么此时的选择器优先级就要通过权重叠加的方法来计算,判断最终哪个选择器优先级最高会生效。
权重叠加计算公式:
比较规则:
- 从左往右优先级一次递减
- 先比较第一级,结果出来了其他不用看,如果相同个数则继续比较下去
- 如果最终全部数字相同,则按层叠性来显示(后面的)
案例演示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* (行内,id,类,标签) */
/* (0,1,0,1) */
div #one{
color: orange;
}
/* (0,0,2,0) */
.father .son{
color: skyblue;
}
/* (0,0,1,1) */
.father p{
color: purple;
}
/* (0,0,0,2) */
div p{
color: pink;
}
</style>
</head>
<body>
<div class="father">
<p class="son" id="one">p标签</p>
</div>
</body>
</html>
最终显示的是橙色,第二级比较出来。