CSS(三)| 继承性和层叠性
css有两大特性:继承性和层叠性
1. 继承性
给父级设置一些属性,子级继承了父级的该属性,这就是我们的css中的继承。
记住:有一些属性是可以继承下来 : color 、 font-*、 text-*、line-* 。主要是文本级的标签元素。
一些盒子元素属性,定位的元素(浮动,绝对定位,固定定位)不能继承。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> /*设置div颜色*/ div { color: red; } </style> </head> <body> <div> <p>韩雪</p> </div> </body> </html>
2. 层叠性
层叠性: 权重大的标签覆盖掉了权重小的标签
权重: 谁的权重大,浏览器就会显示谁的属性
css权重:行内样式 1000 > id选择器 100 > 类选择器010 > 标签选择器001
如何看权重? 数选择器的数量. id 类 标签
1.前提是选中标签,看权重,权重大的优先级要高,如果权重一样大,后面会覆盖掉前面的属性
2.继承来的属性,它们的权重为0, 跟选中的标签没有可比性
3.同是继承来的,谁描述的越近,谁的优先级要高."就近(选中标签)原则"
4.同是继承来的,谁描述的一样近,再回到数权重的状态
例1:选中标签,看权重,权重大的优先级要高
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> /*设置颜色*/ /*1 0 0*/ #box { color: pink; } /*0 1 0*/ .container { color: blue; } /*0 0 1*/ p { color: gray; } </style> </head> <body> <p id="box" class="container">天空是什么颜色</p> </body> </html>
例2:权重一样大,后面会覆盖掉前面的属性(说的是css代码中的顺序)
还是上面那个html结构,如果我设置以下css,会显示什么颜色呢。 <div id='box1' class="wrap1"> <div id="box2" class="wrap2"> <div id="box3" class="wrap3"> <p>再来猜猜我是什么颜色?</p> </div> </div> </div> #box2 .wrap3 p{ color: yellow; } #box1 .wrap2 p{ color: red; }
例3:继承来属性 它们的权重为0,跟选中的标签没有可比性
<div id='box1' class="wrap1"> <div id="box2" class="wrap2"> <div id="box3" class="wrap3"> <p>再来猜猜我是什么颜色?</p> </div> </div> </div> #box1 #box2 .wrap3{ color: red; } #box2 .wrap3 p{ color: green; }
答案是绿色。第一条css设置的属性值,是通过继承性设置成的红色,那么继承来的属性,它的权重为0。它没有资格跟我们下面选中的标签对比。
例4:同是继承来的,谁描述的越近,谁的优先级要高."就近(选中标签)原则"
<div id='box1' class="wrap1"> <div id="box2" class="wrap2"> <div id="box3" class="wrap3"> <p>再来猜猜我是什么颜色?</p> </div> </div> </div> #box1 #box2 .wrap3{ color: red; } .wrap1 #box2{ color: green; }