继承性
css就是在设置属性的,设置的是style的属性。给父级标签设置一些属性,子级标签继承了父级的该属性。
有一些属性是可以继承的:color,font-*,text-*,line-*文本元素
。像一些盒子元素,定位元素(浮动,绝对定位,固定定位是不能继承的。
继承性允许样式不仅应用于特定的html标签元素,而且应用于其后代元素。即孙子标签同时继承爷爷,父亲标签的属性。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>继承性</title>
<style>
.father{
color:red;
font-size:40px;
background-color:green;
}
</style>
</head>
<body>
<div class="father" id="lx">
<p>段落</p>
</div>
</body>
</html>
样式:
层叠性
在多个选择器中有重复样式时,选择器谁的权重大,浏览器就会显示谁的属性。权重大的标签覆盖权重小的标签。
权重的大小比较:数出选择器中包含id,class,标签的数量进行比较。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#d .container{
color:yellow;
}
#box{
color:red;
}
</style>
</head>
<body>
<div id="d">
<p class="container" id="box">段落</p>
</div>
</body>
</html>
id的数量,class的数量,标签的数量
100 010 001
先比较id的数量,如果id的数量多就不会往后比较了,如果id的数量一致,在比较class,以此类推再比较标签的数量。所有选择器权重一样大,在style中后写的显示。
如果没有被选中标签元素,权重为0,其意思是你当前看的是p标签的样式,如果选择器没有选择到p标签,该选择器的权重为0.如果权重都为0
,谁离p标签近,就采用谁的样式。
样式:
!important
在样式后加!important
表示其属性权重无限大。
p{
color:red !important;
}
是不影响继承来的权重,只影响选中的元素。
不建议使用。
层叠性权重相同的效果展示
权重相同选择在style中后写的样式,下面就来验证一下:
第一种写法:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
/*1 1 1*/
#box2 .c3 p{
color:blue;
}
/*1 1 1, 显示*/
#box1 .c2 p{
color: red;
}
</style>
</head>
<body>
<div id="box1" class="c1">
<div id="box2" class="c2">
<div id="box3" class="c3">
<p>段落</p>
</div>
</div>
</div>
</body>
</html>
第二种写法,交换两个样式的位置:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#box1 .c2 p{
color: red;
}
#box2 .c3 p{
color:blue;
}
</style>
</head>
<body>
<div id="box1" class="c1">
<div id="box2" class="c2">
<div id="box3" class="c3">
<p>段落</p>
</div>
</div>
</div>
</body>
</html>
权重都为0的效果展示
权重都为0,什么情况下选择器的权重为0?
如果属性都是被继承下来的,权重为0.
采用就近原则,谁描述的近,就显示谁的属性,也就是说谁离目标标签近,选用谁的样式。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#box1 .c2{
color:red;
}
.c1{
color:green;
}
</style>
</head>
<body>
<div id="box1" class="c1">
<div id="box2" class="c2">
<p>段落</p>
</div>
</div>
</body>
</html>