理解CSS的选中器优先级和!important权重
发布时间:01/01 来源:未知 浏览:
关键词:
引荐:css视频教程
CSS中的选中器优先级与!important权重
.class
选中器要高于标签选中器。#id
选中器要高于.class
选中器。- 标签选中器是优先级最低的选中器。
!important
的属性它的权重值优先级最高的,大于所有的选中器。
标签选中器和.class选中器
让我们进入标签选中器和.class
选中器谁的优先级高实践,实践内容如:将HTML
页面中的h2
标签设定文本色彩。
代码块
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>优先级</title> <style> h2{ color: red; /*红色*/ } .box{ color: springgreen; /*绿色*/ } </style> </head> <body> <h2 class="box">微笑是最初的崇奉</h2> </body> </html>
结果图
.class选中器和id选中器
让我们进入.class
选中器和id
选中器谁的优先级高实践,实践内容如:将HTML
页面中的h2
标签设定文本色彩。
代码块
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>优先级</title> <style> h2{ color: red; /*红色*/ } .box{ color: springgreen; /*绿色*/ } #box{ color:blue; /*蓝色*/ } </style> </head> <body> <h2 class="box" id="box">微笑是最初的崇奉</h2> </body> </html>
结果图
!important权重使用
此刻我们知道了标签选中器优先级最低,那么笔者将标签选中器增加!important
属性呢,谁的优先级更高呢?
!important权重使用格局如下:
color: red !important; /*红色*/
留意:属性:值 !important
属性值用空格隔开即可。
让我们进入 !important
属性使用实践,看看!important
属性威力有多大哈。
代码块
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>!important使用</title> <style> h2{ color: red !important; /*红色*/ } .box{ color: springgreen; /*绿色*/ } #box{ color:blue; /*蓝色*/ } </style> </head> <body> <h2 class="box" id="box">微笑是最初的崇奉</h2> </body> </html>
结果图
总结
优先级从低到高如:标签选中器、.class
选中器、#id
选中器、!important
属性