CSS样式定义的优先级顺序总结

CSS样式定义的优先级顺序总结

层叠优先级是:

浏览器缺省 < 外部样式表 < 内部样式表 < 内联样式

其中样式表又有:

类选择器 < 类派生选择器 < ID选择器 < ID派生选择器

派生选择器以前叫上下文选择器,所以完整的层叠优先级是:

浏览器缺省 < 外部样式表 < 外部样式表类选择器 < 外部样式表类派生选择器 < 外部样式表ID选择器 < 外部样式表ID派生选择器 < 内部样式表 < 内部样式表类选择器 < 内部样式表类派生选择器 < 内部样式表ID选择器 < 内部样式表ID派生选择器 < 内联样式...共12个优先级

为了说明该问题,请参见下面的例子说明。

[html] view plaincopy
 
  1. <html>  
  2. <head>  
  3.     <title></title>  
  4.     <style type="text/css">  
  5.         div { color: #00FF00 } /* 绿色 */  
  6.         .a1 { color: #0000FF } /* 蓝色 */  
  7.         .a1 div { color: #00FFFF } /* 青色 */  
  8.         .a2 { color: #FF0000 } /* 红色 */  
  9.         #a2 { color: #FFFF00 } /* 黄色 */  
  10.         #a2 div { color: #FF00FF } /* 紫色 */  
  11.     </style>  
  12. </head>  
  13. <body>  
  14.   <div>我是绿色,内部样式表优先于浏览器缺省</div>  
  15.   <div class="a2">我是红色,类选择器优先于内部样式表</div>  
  16.   <div class="a2" id="a2">我是黄色,ID选择器优先于类选择器</div>  
  17.   <div class="a1">  
  18.       <span>我是蓝色,类选择器优先于内部样式表</span>  
  19.       <div>我是青色,类派生选择器优先于类选择器</div>  
  20.       <div class="a2">我还是青色,类派生选择器优先于所有类选择器</div>  
  21.       <div id="a2">  
  22.           <span>我是黄色,ID选择器优先于类派生选择器</span>  
  23.           <div>我是紫色,ID派生选择器优先于类派生选择器</div>  
  24.           <div class="a1">我还是紫色,ID派生选择器优先于所有类选择器</div>  
  25.           <div class="a1" id="a1">我还是紫色,ID派生选择器优先于所有ID选择器</div>  
  26.           <div class="a1" id="a1" style="color:#000000;">我是黑色,内联样式驾到闲杂人等退下</div>  
  27.       </div>  
  28.   </div>  
  29. </body>  
  30. </html>  


 运行后的效果图:

另外,如果同一个元素在没有其他样式的作用影响下,其Class定义了多个并以空格分开,其优先级顺序为:

一个元素同时应用多个class,后定义的优先(即近者优先),加上!important者最优先!

[html] view plaincopy
 
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />  
  5. <title></title>  
  6. <style type="text/css">  
  7. .a2 {  
  8.     font-size: 18pt;  
  9.     color: #0000FF!important;  
  10. }  
  11. .a1 {  
  12.     font-size: 9pt;  
  13.     color: #FF0000;  
  14. }  
  15. </style>  
  16. </head>  
  17.   
  18. <body>  
  19. <br />  
  20. <span class="a1">a1</span><br />  
  21. <span class="a2">a2</span><br />  
  22. <span class="a2 a1">a2 a1</span><br />  
  23. <span class="a1 a2">a1 a2</span><br />  
  24. </body>  
  25. </html>  


运行后的效果图:

原文地址:https://www.cnblogs.com/telwanggs/p/5099235.html