CSS 书写顺序推荐

192 阅读1分钟

CSS 书写顺序推荐按照以下的原则进行:

  1. 位置属性:position, top, right, bottom, left
  2. 大小属性:width, height
  3. 盒模型属性:margin, padding, border
  4. 显示属性:display, visibility, float
  5. 装饰属性:color, background, box-shadow 等
  6. 文本属性:font, line-height, text-align 等
  7. 其他属性: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;
}

  


这样的顺序不是硬性规定的,主要是为了提供一个清晰的思路,使得团队开发中的代码风格统一,提高代码的可维护性。