您的位置:首页 > Web前端 > CSS

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

2016-06-30 11:07 429 查看
CSS样式定义的优先级顺序总结

 

层叠优先级是:

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

 

其中样式表又有:

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

 

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

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

 

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

[html] view
plain copy

<html>  

<head>  

    <title></title>  

    <style type="text/css">  

        div { color: #00FF00 } /* 绿色 */  

        .a1 { color: #0000FF } /* 蓝色 */  

        .a1 div { color: #00FFFF } /* 青色 */  

        .a2 { color: #FF0000 } /* 红色 */  

        #a2 { color: #FFFF00 } /* 黄色 */  

        #a2 div { color: #FF00FF } /* 紫色 */  

    </style>  

</head>  

<body>  

  <div>我是绿色,内部样式表优先于浏览器缺省</div>  

  <div class="a2">我是红色,类选择器优先于内部样式表</div>  

  <div class="a2" id="a2">我是黄色,ID选择器优先于类选择器</div>  

  <div class="a1">  

      <span>我是蓝色,类选择器优先于内部样式表</span>  

      <div>我是青色,类派生选择器优先于类选择器</div>  

      <div class="a2">我还是青色,类派生选择器优先于所有类选择器</div>  

      <div id="a2">  

          <span>我是黄色,ID选择器优先于类派生选择器</span>  

          <div>我是紫色,ID派生选择器优先于类派生选择器</div>  

          <div class="a1">我还是紫色,ID派生选择器优先于所有类选择器</div>  

          <div class="a1" id="a1">我还是紫色,ID派生选择器优先于所有ID选择器</div>  

          <div class="a1" id="a1" style="color:#000000;">我是黑色,内联样式驾到闲杂人等退下</div>  

      </div>  

  </div>  

</body>  

</html>  

 运行后的效果图:



 

 

 

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

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

[html] view
plain copy

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  

<html xmlns="http://www.w3.org/1999/xhtml">  

<head>  

<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />  

<title></title>  

<style type="text/css">  

.a2 {  

    font-size: 18pt;  

    color: #0000FF!important;  

}  

.a1 {  

    font-size: 9pt;  

    color: #FF0000;  

}  

</style>  

</head>  

  

<body>  

<br />  

<span class="a1">a1</span><br />  

<span class="a2">a2</span><br />  

<span class="a2 a1">a2 a1</span><br />  

<span class="a1 a2">a1 a2</span><br />  

</body>  

</html>  

运行后的效果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: