以前一直以为css代码,没什么可优化之处,直到前几天看到一篇文章,用良好的CSS书写习惯来写CSS代码,这样会提高代码的阅读体验。
CSS书写顺序
1.位置属性(position, top, right, z-index, display, float, clear等)
2.大小(width, height, padding, margin)
3.文字系列(font, line-height, letter-spacing, color, text-align等)
4.背景(background, border等)
5.其他(animation, transition等)
下面是Mozilla Firefox所建议的CSS书写顺序,对我们的代码书写很有参考价值:
mozilla.org Base Styles
* maintained by fantasai
* (classes defined in the Markup Guide -http://mozilla.org/contribute/writing/markup)
*/
/* 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
*
*/<--文章内容结束标识,勿删!!--> <--page-->
css编码的顺序问题,这是一个非常微小的细节问题,但涉及到团队协作以及让您的编码更加工整,强烈推荐以一定的顺序来进行编码。看下面的例子:
A:
.wrap{
height:130px;
border:none;
line-height:130px;
font-size:48px;
color:#c7c7cd;
padding:0 10px;
width:74%;
}
B:
.wrap{
width:74%;
height:130px;
padding:0 10px;
border:none;
color:#c7c7cd;
font-size:48px;
line-height:130px;
}
我们发现,B段代码明显要比A段代码工整很多,这样在修改样式时可以很快的找到相关属性,进而进行调整。而A段代码看上去很杂乱,如果定义的属性足够多,根本不清楚写在了什么地方。以B段代码的形式按一定的顺序进行编码也有利于团队协作共同开发。