整理:电子商务专业实践网
七、避免不必要的重复
尽可能组合重复的规则。
代码如下:
// 糟糕
.someclass {
color: red;
background: blue;
font-size: 15px;
}
.otherclass {
color: red;
background: blue;
font-size: 15px;
}
// 好的
.someclass, .otherclass {
color: red;
background: blue;
font-size: 15px;
}
八、尽可能精简规则
在上面规则的基础上,你可以进一步合并不同类里的重复的规则。
代码如下:
// 糟糕
.someclass {
color: red;
background: blue;
height: 150px;
width: 150px;
font-size: 16px;
}
.otherclass {
color: red;
background: blue;
height: 150px;
width: 150px;
font-size: 8px;
}
// 好的
.someclass, .otherclass {
color: red;
background: blue;
height: 150px;
width: 150px;
}
.someclass {
font-size: 16px;
}
.otherclass {
font-size: 8px;
}
九、避免不明确的命名约定
最好使用表示语义的名字。一个好的CSS类名应描述它是什么而不是它像什么。
十、避免 !importants
其实你应该也可以使用其他优质的选择器。
十一、遵循一个标准的声明顺序
虽然有一些排列CSS属性顺序常见的方式,下面是我遵循的一种流行方式。
代码如下:
.someclass {
/* Positioning */
/* Display & Box Model */
/* Background and typography styles */
/* Transitions */
/* Other */
}
十二、组织好的代码格式
代码的易读性和易维护性成正比。下面是我遵循的格式化方法。
代码如下:
// 糟糕
.someclass-a, .someclass-b, .someclass-c, .someclass-d {
...
}
// 好的
.someclass-a,
.someclass-b,
.someclass-c,
.someclass-d {
...
}
// 好的做法
.someclass {
background-image:
linear-gradient(#000, #ccc),
linear-gradient(#ccc, #ddd);
box-shadow:
2px 2px 2px #000,
1px 4px 1px 1px #ddd inset;
}
显然,这里只讲述了少数的规则,是我在我自己的CSS中,本着更高效和更易维护性而尝试遵循的规则。如果你想阅读更多的知识,我建议阅读MDN上的编写高效的CSS和谷歌的优化浏览器渲染指南
|