从CSS代码存放位置看权重优先级:内嵌样式 > 内部样式表 > 外联样式表。其实这个基本可以忽视之,大部分情况下CSS代码都是使用外联样式表。
从样式选择器看权重优先级:important > 内嵌样式 > ID > 类 > 标签 | 伪类 | 属性选择 > 伪对象 > 继承 > 通配符。
- important的权重为1,0,0,0
- ID的权重为0,1,0,0
- 类的权重为0,0,1,0
- 标签的权重为0,0,0,1
- 伪类的权重为0,0,1,0
- 属性的权重为0,0,1,0
- 伪对象的权重为0,0,0,1
- 通配符的权重为0,0,0,0
<html>
<head>
<style type="text/css">
#left{color:black!important;} /*1,1,0,0*/
#container #left{color:red;} /*0,2,0,0*/
#left{color:green!important;} /*1,1,0,0*/
.container #left{color:blue;} /*0,1,1,0*/
</style>
</head>
<body>
<div class="container" id="container">
<span id="left">这到底是什么颜色啊?</span>
</div>
</body>
</html>
<head>
<style type="text/css">
#left{color:black!important;} /*1,1,0,0*/
#container #left{color:red;} /*0,2,0,0*/
#left{color:green!important;} /*1,1,0,0*/
.container #left{color:blue;} /*0,1,1,0*/
</style>
</head>
<body>
<div class="container" id="container">
<span id="left">这到底是什么颜色啊?</span>
</div>
</body>
</html>