前段入门之CSS二
1 如何引入CSS?
1.1 行间样式
在HTML元素开始标签中添加 style
属性,属性值由分号隔开的CSS声明构成。
<h1 style=color:red;text-align:center;>中间红色</h1>
<h2 style=color:green;text-align:center;>中间绿色</h2>
1.2 页面样式
在HTML文档 <head>
元素中加入 <style>
元素,元素内容为CSS规则。
<head>
<style type="text/css">
h1 {
text-align: center;
color:red;
}
h2{
text-align:center;
color:green;
}
</style>
</head>
<h1 >中间红色</h1>
<h2 >中间绿色</h2>
1.3 外部样式
重新创建一个CSS文件,并在HTML文档 <head>
元素中加入<link>
元素。
/* waibu.css文件内容 */
h1 {
text-align: center;
color:red;
}
h2{
text-align:center;
color:green;
}
<head>
<link rel="stylesheet" type="text/css" href="waibu.css">
</head>
<h1 >中间红色</h1>
<h2 >中间绿色</h2>
2 CSS声明权重及优先性
当CSS声明有冲突时,如下面这个例子:
p{
background-color: blue!important;
}
#idDiv p{
background-color: red;
}
#idDiv .classP{
background-color: yellow;
}
.classDiv .classP{
background-color: green;
}
<div class="classDiv" id="idDiv">
<p class="classP" id="idP">
123456789
</p>
</div>
依次操作 | 渲染结果 |
---|---|
无 | |
| |
交换red 与yellow | |
、
|
元素选择器p
与三个后代选择器#idDiv p
、#idDiv .classP
和.classDiv .classP
同时对<p>
元素的background-color
的属性进行了声明。这时,浏览器内核会根据CSS声明的权重值进行渲染。
CSS声明 | 选择器 | 权重(256进制) | ||
---|---|---|---|---|
important声明 | 任意 | infinity | ||
行间样式 | 无 | 1000 | ||
页面样式或外部样式 | ||||
单个选择器 | id选择器 | 100 | ||
属性选择器 | 10 | |||
类选择器 | 10 | |||
伪类选择器 | 10 | |||
元素选择器 | 1 | |||
伪元素选择器 | 1 | |||
通用选择器 | 0 | |||
复合选择器 | 单个选择器权重之和 |
•p
的权重为(
i
m
p
o
r
t
a
n
t
important
important声明):
i
n
f
i
n
i
t
y
infinity
infinity
•#idDiv p
的权重为(id选择器+属性选择器):
100
+
10
=
110
100+10=110
100+10=110
#idDiv .classP
的权重为(id选择器+类别选择器):
100
+
10
=
110
100+10=110
100+10=110
.classDiv .classP
的权重为(类别选择器+类别选择器):
10
+
10
=
20
10+10=20
10+10=20
所以声明权重值background-color:blue
>background-color:red
=background-color:yellow
>background-color:green
所以,当CSS声明发生冲突时,浏览器渲染权值较高的声明,当冲突声明权值相同时,浏览器渲染靠后的声明。
补充说明:
•
i
m
p
o
r
t
a
n
t
important
important声明:在一般CSS声明后加!important
。
• 在电脑中,
i
n
f
i
n
i
t
y
infinity
infinity也是一个具体的值。
相关文章链接:
前段入门之CSS一 | 前段入门之CSS二| 前段入门之CSS三
前段入门之HTML一 | 前段入门之HTML二
本人由于之前用Flask&Dash框架快速开发数据分析Web APP 开始了解到前段工程师这个行业,并产生了一些兴趣,现在打算从头开始学习前段开发的一些知识,写博客来记录一下学习的过程。欢迎各位一起讨论学习,如有错误的地方或者建议,恳请在评论区批评和指导,博客不定期修改和更新。