CSS代码规范

Posted by Nutlee on 2016-04-26

以组件为单位组织代码段

Class和ID

  • 使用语义化、通用的命名方式;
  • 使用连字符 - 作为 ID、Class 名称界定符,不要驼峰命名法和下划线;
  • 避免选择器嵌套层级过多,尽量少于 3 级;
  • 避免选择器和 Class、ID 叠加使用;

声明块格式

  • 一般以逗号分隔的属性值,每个逗号后应添加一个空格;
  • rgb()、rgba()、hsl()、hsla() 或 rect() 括号内的值,逗号分隔,但逗号后不添加一个空格;
  • 对于属性值或颜色参数,省略小于 1 的小数前面的 0 (例如,.5 代替 0.5;-.5px 代替-0.5px);
  • 十六进制值应该全部小写和尽量简写,例如,#fff 代替 #ffffff;
  • 避免为 0 值指定单位,例如,用 margin: 0; 代替 margin: 0px;;

声明顺序

  • Positioning   //position left right top
  • Box model   //width height margin border
  • Typographic   //字体字号 字排版 处理
  • Visual   //background-color color
    opacity
  • other //cursor


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    .declaration-order {
    /* Positioning */
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 100;
    /* Box model */
    display: block;
    box-sizing: border-box;
    width: 100px;
    height: 100px;
    padding: 10px;
    border: 1px solid #e5e5e5;
    border-radius: 3px;
    margin: 10px;
    float: right;
    overflow: hidden;
    /* Typographic */
    font: normal 13px "Helvetica Neue", sans-serif;
    line-height: 1.5;
    text-align: center;
    /* Visual */
    background-color: #f5f5f5;
    color: #fff;
    opacity: .8;
    /* Other */
    cursor: pointer;
    }

url( ) 、属性选择符、属性值使用双引号。

不要使用 @import

性能优化

  • 慎重选择高消耗的样式

    1
    2
    3
    4
    5
    box-shadows
    border-radius
    transparency
    transforms
    CSS filters(性能杀手)
  • 避免过分重排

  • 正确使用 Display 的属性,Display 属性会影响页面的渲染,请合理使用。
    • display: inline后不应该再使用 width、height、margin、padding 以及 float;
    • display: inline-block 后不应该再使用 float;参考 CSS权重和display水平
    • display: block 后不应该再使用 vertical-align;
    • display: table-* 后不应该再使用 margin 或者 float;
  • 不滥用 Float 计算量较大
  • CSS 选择器是从右到左进行规则匹配,注意开销 ,只要当前选择符的左边还有其他选择符,样式系统就会继续向左移动,直到找到和规则匹配的选择符,或者因为不匹配而退出。我们把最右边选择符称之为关键选择器。

    • 避免使用通用选择器
    • 避免使用标签或 class 选择器限制 id 选择器
    • 避免使用标签限制 class 选择器
    • 避免使用多层标签选择器。使用 class 选择器替换,减少css查找
    • 避免使用子选择器
    • 使用继承

      1
      2
      3
      4
      /* Not recommended */
      #bookmarkMenuItem > .menu-left { list-style-image: url(blah) }
      /* Recommended */
      #bookmarkMenuItem { list-style-image: url(blah) }

参考资料:
前端开发规范手册CSS