CSS 书写顺序推荐按照以下的原则进行:
- 位置属性:position, top, right, bottom, left
- 大小属性:width, height
- 盒模型属性:margin, padding, border
- 显示属性:display, visibility, float
- 装饰属性:color, background, box-shadow 等
- 文本属性:font, line-height, text-align 等
- 其他属性:cursor, z-index 等
这样的顺序有助于代码的可读性,并且在某些情况下,也可以提高性能,因为浏览器可以更有效地处理它。
示例代码:
/* Positioning */
position: relative;
top: 0;
right: 0;
bottom: 0;
left: 0;
/* Box model */
display: block;
float: right;
width: 100px;
height: 100px;
margin: 5px;
padding: 10px;
border: 1px solid #000;
/* Background and decoration */
background-color: #f00;
background-image: url('image.jpg');
background-repeat: no-repeat;
/* Font */
font-size: 16px;
line-height: 1.5;
font-weight: bold;
color: #fff;
/* Misc */
text-align: center;
visibility: hidden;
cursor: pointer;
z-index: 10;
}
这样的顺序不是硬性规定的,主要是为了提供一个清晰的思路,使得团队开发中的代码风格统一,提高代码的可维护性。