css
命名规范
- 长名称或词组可以使用
横杠来为选择器命名,如song-lists - 不建议使用
_下划线命名 - 不要纯数字、中文等命名,尽量使用英文字母来表示
选择器
- 当一个 rule 包含多个 selector 时,每个选择器声明必须独占一行。
/* good */
.post,
.page,
.comment {
line-height: 1.5;
}
/* bad */
.post, .page, .comment {
line-height: 1.5;
}
属性定义后必须以分号结尾
/* good */
.selector {
margin: 0;
}
/* bad */
.selector {
margin: 0
}
属性书写顺序
- [建议] 同一 rule set 下的属性在书写时,应按功能进行分组,并以 Formatting Model(布局方式、位置) > Box Model(尺寸) > Typographic(文本相关) > Visual(视觉效果) 的顺序书写,以提高代码的可读性。
解释:
- Formatting Model 相关属性包括:
position/top/right/bottom/left/float/display/overflow等 - Box Model 相关属性包括:
border/margin/padding/width/height等 - Typographic 相关属性包括:
font/line-height/text-align/word-wrap等 - Visual 相关属性包括:
background/color/transition/list-style等
另外,如果包含 content 属性,应放在最前面。
示例:
.sidebar {
/* formatting model: positioning schemes / offsets / z-indexes / display / ... */
position: absolute;
top: 50px;
left: 0;
overflow-x: hidden;
/* box model: sizes / margins / paddings / borders / ... */
width: 200px;
padding: 5px;
border: 1px solid #ddd;
/* typographic: font / aligns / text styles / ... */
font-size: 14px;
line-height: 20px;
/* visual: colors / shadows / gradients / ... */
background: #f5f5f5;
color: #333;
-webkit-transition: color 1s;
-moz-transition: color 1s;
transition: color 1s;
}
清除浮动
- [建议] 当元素需要撑起高度以包含内部的浮动元素时,通过对伪类设置
clear或触发BFC的方式进行clearfix。尽量不使用增加空标签的方式。
解释:
触发 BFC 的方式很多,常见的有:
- float 非 none
- position 非 static
- overflow 非 visible
如希望使用更小副作用的清除浮动方法,参见 A new micro clearfix hack 一文。
另需注意,对已经触发 BFC 的元素不需要再进行 clearfix。
!important
- [建议] 尽量不使用
!important声明。 - [建议] 当需要强制指定样式且不允许任何场景覆盖时,通过标签内联和
!important定义样式。
解释:
必须注意的是,仅在设计上 确实不允许任何其它场景覆盖样式 时,才使用内联的 !important 样式。通常在第三方环境的应用中使用这种方案。下面的 z-index 章节是其中一个特殊场景的典型样例。