十分钟学习CSS_IN_DEPTH中的一个知识点之默认样式还是选择器样式
我们有如下的一个html文件,那么h2的样式是什么样子的呢?换言之h2的字体大小,颜色等等是怎样的呢?
<!doctype html>
<html>
<body>
<h2>hello</h2>
</body>
</html>
这就是这次要讨论的问题。
如果我们不使用任何的css,毫无疑问上面的文本同样可以在浏览器中显示出来。同时可以注意到在不同的浏览器中打开来看的话,字体的大小,外观可能略有些不同。这就是浏览器的 默认样式。
当我们为h2添加一些样式。
<!doctype html>
<html>
<head>
<style>
h2 {
color: red;
}
</style>
</head>
<body>
<h2>hello</h2>
</body>
</html>
此时h2在浏览器中显示的颜色将会变成红色。在这里我们在style中为h2设置了红色的字体颜色。
我们将在style中定义的以及通过link引入的外部样式表称为用户定义的样式。从上面的结果大家应该能够想到用户定义的样式的优先级 > 默认样式。
现在我们来一起做一个起名字的游戏,让我们将style中的h2称为selector,同样大家知道class(如 .btn)和id(如 #header)也是selector。将color:red;称为descriptor。那么{}中所有的descriptor的集合称为descriptor block。这样selector和descriptor block组合起来就构成了rule。
现在我们来比较一下不同selector的优先级
<!doctype html>
<html>
<head>
<style>
h2 {
color: green;
}
.danger {
color: red;
}
#sea {
color: blue;
}
</style>
</head>
<body>
<h2 id="sea" class="danger">hello</h2>
</body>
</html>
最后的结果是h2会显示为蓝色-大海的颜色。
如果我们为h2添加一个inline style
<!doctype html>
<html>
<head>
#sea {
color: blue;
}
</head>
<body>
<h2 style="color: yellow;">hello</h2>
</body>
</html>
此时h2的颜色会显示为黄色。这里我们有一个关于优先级的结论: inline style > id > class > tag。 并且有这样的一个计算方法:
| num | selector | id | class | tag | sum |
|---|---|---|---|---|---|
| 1 | h2.first | 0 | 1 | 1 | 0,1,1 |
| 2 | .first .danger | 0 | 2 | 0 | 0,2,0 |
| 3 | #sea | 1 | 0 | 0 | 1,0,0 |
最终的优先级是3 > 2 > 1
note: 如果选择器的优先级相同则在style中后定义的rule具有更高的优先级。
最后关于 !important,请看下面的例子:
<!doctype html>
<html>
<head>
h2 {
color: blue !important;
}
</head>
<body>
<h2 style="color: yellow;">hello</h2>
</body>
</html>
inline sytle 具有很高的优先级了,同时其优先级是要比tag高的,但这里h2的颜色是蓝色。原因是important会将descriptor的优先级提升到最高,当然如果你在inline style中用important的话,无疑其优先级将是最高的。
至此我们了解了css中样式的优先级和计算的方法。
希望大家阅读CSS_IN_DEPTH去了解更加完整的信息