css的特性-继承性
一、css的某些属性具有继承性(Inherited):
-
如果一个属性具有继承性,那在该元素设置之后,它的后代元素都可以继承这个属性。
-
<!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> .box { color: #f00; } </style> </head> <body> <div class="box"> <h2>我是h2</h2> <p>我是p元素</p> <span>我是span元素</span> </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> .box { color: #f00; font-size: 2em; } .box p { color: black; } </style> </head> <body> <div class="box"> <h2>我是h2</h2> <p>我是p元素</p> <span>我是span元素</span> </div> </body> </html>
-
二、如何知道一个属性是否有继承性呢
- 常见的font-size/font-family/font-weight/line-height/color/text-align都具有继承性;(一般和文本相关的)
- 这些不用刻意去记, 用的多自然就记住了;
- 记不住直接去查MDN文档就行,例如:
注意继承过来的不是设置值,而是计算值
三、强制继承(了解)
-
如果一个属性不具备继承性,但你又想让它后代继承的话,可以使用强制继承,但不推荐
-
-
强制继承后的
-
-
<!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> .box { color: #f00; font-size: 2em; border: 1px solid #000; } .box p { color: black; border: inherit; } </style> </head> <body> <div class="box"> <h2>我是h2</h2> <p>我是p元素</p> <span>我是span元素</span> </div> </body> </html>