css属性顺序是css良好编码风格的一部分,有助于提高代码可读性,便于发现代码问题,有利于团队合作。下面总结一些比较受欢迎的css属性顺序。
1. 传说中Mozilla建议的css属性书写顺序(实为fantasai建议的顺序):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
/*mozilla.org Base Styles
* maintained by fantasai
*/
/* Suggested order:
//显示属性
* display
* list-style
* position
* float
* clear
//自身属性
* width
* height
* margin
* padding
* border
* background
//文本属性
* color
* font
* text-decoration
* text-align
* vertical-align
* white-space
* other text
* content
*/
|
2. 字母排序:
Trevor Davis在《5 Ways to Instantly Write Better CSS》中推荐用字母排序。
3. 传说中淘宝的css属性顺序:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
/*显示属性*/
display
position
float
clear
cursor
…
/*盒模型*/
margin
padding
width
height
/*排版*/
vertical-align
white-space
text-decoration
text-align
…
/*文字*/
color
font
content
/*边框背景 为什么要把boder和background放在最后的原因是修改的频率会较之前的频繁,放在最后查看起来方便,哈哈。*/
border
background
|
1
2
3
4
5
6
7
|
Display & Flow
Positioning
Dimensions
Margins, Padding, Borders, Outline
Typographic Styles
Backgrounds
Opacity, Cursors, Generated Content
|
5. 我自己总结的顺序:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
/* 属性的顺序(结合属性的类型、字母序及属性关系):
//显示属性
1. clear
2. cursor
3. display
4. float
5. list-style
6. position
//盒模型
1. width
2. height
3. margin
4. padding
//排版
1. text-align
2. text-decoration
3. vertical-align
4. white-space
//文本属性
1. color
2. content
3. font
//边框背景(因为修改最频繁,所以放在最后)
1. background
2. border
*/
|
除了css属性之外,其实css选择器本身也有顺序。我一般采用两种排序方法。
1. 按css选择器在html页面中出现的先后顺序。
2. 按选择器的优先级及字母顺序。
1
2
3
4
5
6
7
|
/* 选择器的排列顺序(结合css选择器权重及字母序):
1. html选择器(标签选择器)
2. class选择器(类选择器)
3. id选择器
* 同一类选择器中按照字母顺序排列先后
* 基本选择器在前,组合选择器在后,伪类选择器在最后
*/
|
注意:css的选择器有自己的权重,当权重一样时,会采用“层叠原则” ,即后定义的会被应用。 如:
1
2
|
p{
color
:yellow}
p{
color
:
red
}
|
作用到这里<p>我的什么颜色呢?</p>,结果是red。