CSS书写规范

288 阅读1分钟

使用css缩写属性

CSS有些属性是可以缩写的,比如padding,margin,font等等,这样精简代码同时又能提高开发者开发效率。

    
    .box{
        font-size:12px;
        font-family:serif;
        line-height:1.6;
        padding-top:0;
        padding-left:1px;
        padding-right:2px;
        padding-bottom:3px;
    }
    <!--✖-->
    
    
    .box{
        font: 12px/1.6 serif;
        padding:0 2px 3px 1px;
    }
    <!--✔-->

去掉小数点前的 "0"

    font-size:0.8em;   // ✖
    
    font-size:.8em;   // ✔

简写命名

很多用户都喜欢简写类名,但前提是要让人看懂你的命名才能简写!

    <!--✖-->
    .navigation {
        
    }
    .atr {
        
    }
    <!--✔-->
    #nav {
        
    }
    .author {
        
    }

16进制颜色代码缩写

有些颜色代码是可以缩写的,我们尽量缩写吧,提高用户体验为主。

    color:#eebbcc;   // ✖
    
    color:#ebc;   // ✔

font 简写

    顺序:font-style | font-variant | font-weight | font-size | line-height | font-family
    
    例如:.font{font:italic small-caps bold 12px/1.5em arial,verdana;}
    
    
    注意:

    1、简写时,font-sizeline-height只能通过斜杠/组成一个值,不能分开写。
    2、顺序不能改变.这种简写方法只有在同时指定font-sizefont-family属性时才起作用。而且,如果你没有设定font-weight, font-style, 以及 font-varient ,他们会使用默认值

CSS书写顺序

1、位置属性(position, top, right, z-index, display, float等)
2、大小(width, height, padding, margin)
3、文字系列(font, line-height, letter-spacing, color, text-align等)
4、背景(background, border等)
5、其他(animation, transition等)

    // 错误写法
   .box{
       color:red;
       z-index:1;
       background-color:#9e0;
       display:inline-block;
       font-size:12px;
   }
   // 正确写法
   .box{
        z-index:1;
        display:inline-block;
        font-size:12px;
        color:red;
        background-color:#9e0;
       
   }

按照上述1 2 3 4 5的顺序进行书写,目的:减少浏览器reflow(回流),提升浏览器渲染dom的性能。