什么是!important
!important是一个修饰符,语法是选择器{属性:属性值 !important}。作用是更改默认的CSS样式优先级。
示例
注意中间要有空格,不能有分号
- 正确示例
.p{color:#blue !important}
- 错误示例
.p{color:#blue;!important}
.p{color:#blue!important}
实际用法
- 只有一条语句使用!important修饰。按照该语句样式显示,最后显示为橙色。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .box1 { color: green; } #d1 { color: red; } p { color: orange !important; } </style> </head> <body> <p id="d1" class="box1">文字颜色</p> </body> </html>
- 如果有层叠的语句都使用!important修饰,那么将按照语句所在选择器的权重大小来起作用,最后显示红色。
id选择器>类选择器>标签选择器
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .box1 { color: green !important; } #d1 { color: red !important; } p { color: orange !important; } </style> </head> <body> <p id="d1" class="box1">文字颜色</p> </body> </html>
- 如果是继承过来的样式,他的权重为0,加上!important属性权重仍为0,即!important不能提升权重为0的样式,结果显示为橙色。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .box1 { color: green !important; } p { color: orange;} </style> </head> <body> <div class="box1"> <p>文字颜色</p> </div> </body> </html>