以下总结自《CSS揭秘》,一本不错的书,可以学到一些 CSS 的进阶技巧
现在要设置一个背景色,有两种写法:
// 简写
background: red;
// 非简写
background-color: red;
复制代码
前者是简写,可以确保得到一个纯色背景;后者不一定能得到想要的结果,因为可能会有一条 background-image
声明在起作用。
展开式写法并不会帮助你清空所有相关的其他属性,从而可能会干扰你想要达到的效果。
使用原则
合理使用简写是一种良好的防卫性编码方式,可以抵御未来的风险。
如果要明确去覆盖某个具体的展开式属性并保留其他相关样式,就用展开式写法。
配合使用
配合使用展开式属性和简写属性,有时可能减少一些重复,提高代码可维护性。
background: url(tr.png) no-repeat top right,
url(br.png) no-repeat bottom right,
url(bl.png) no-repeat bottom left;
// 配合使用
background: url(tr.png) top right,
url(br.png) bottom right,
url(bl.png) bottom left;
background-repeat: no-repeat;
复制代码
这样只需要修改一处,就可以改变所有的 background-repeat
了。
参考
- 《CSS揭秘》