您的位置:首页 > Web前端 > css > 正文

如何编写更好的CSS

更多 时间:2014-7-27 类别:Web前端 浏览量:1467

如何编写更好的CSS

如何编写更好的CSS

1,不要使用全局重置

全局重置是一个禁忌的写法,这种方法毫无效率,你可能需要为每个元素重新设置 margin 和 padding 值。

 

不好:


 *{ margin:0; padding:0; } 

好:


html, body, li, dl, dt, dd, ul,  h1, h2, h3,  pre, form, label, fieldset, input, p, blockquote, th, td { margin:0; padding:0 } 
table { border-collapse:collapse; border-spacing:0 } 
fieldset, img { border:0 } 
ul { list-style:none } 

 

2、避免过度约束

 

糟糕


ul#someid {..}
.menu#otherid{..}

好的


#someid {..}
#otherid {..}


3、为 ID 和 Class 加上有意义的名字

在起名字之前你最好想想这个名字是否会有歧义,想一个恰如其分的名字将会为你的后期工作减轻很多压力。

 

4、后代选择符最烂

不仅性能低下而且代码很脆弱,html代码和css代码严重耦合,html代码结构发生变化时,CSS也得修改,这是多么糟糕,特别是在大公司里,写html和css的往往不是同一个人。


html li tr td {..}

 

5、避免链式(交集)选择符

我们应该简单的创建一个新的CSS类选择符。

 

糟糕
.menu.left.icon {..}


好的
.menu-left-icon {..}

 

6,利用属性缩写

margin, padding, border, font, background以及color 等值可以速记编写成一行

 

不好:
    li{ 
        font-family:Arial, Helvetica, sans-serif; 
        font-size: 1.2em; 
        line-height: 1.4em; 
        padding-top:5px; 
        padding-bottom:10px; 
        padding-left:5px; 
    } 


好:
    li{ 
        font: 1.2em/1.4em Arial, Helvetica, sans-serif; 
        padding:5px 0 10px 5px; 
    } 

 

7、避免不必要的重复

尽可能组合重复的规则。

 

// 糟糕
.someclass {
 color: red;
 background: blue;
 font-size: 15px;
}

.otherclass {
 color: red;
 background: blue;
 font-size: 15px;
}

// 好的
.someclass, .otherclass {
 color: red;
 background: blue;
 font-size: 15px;
}


8、组织css编码

将css进行组织和分布将会大大方便你的查阅和修改,同时也能够方便与他人的协同工作。这里就是一个小格式。
 

/*-------------------------
    CSS Reset 重置CSS
-------------------------*/ 
 
/*-------------------------
    Generic Classes 一般样式
-------------------------*/ 
 
/*-------------------------
    Layout styles 布局样式
-------------------------*/ 
 
/*-------------------------
    Section specific styles  部分特定样式
-------------------------*/

 

9、尽可能精简规则

可以合并不同类里的重复的规则

 

// 糟糕
.someclass {
 color: red;
 background: blue;
 height: 150px;
 width: 150px;
 font-size: 16px;
}

.otherclass {
 color: red;
 background: blue;
 height: 150px;
 width: 150px;
 font-size: 8px;
}

 

// 好的
.someclass, .otherclass {
 color: red;
 background: blue;
 height: 150px;
 width: 150px;
}

.someclass {
 font-size: 16px;
}

.otherclass {
 font-size: 8px;
}

 

10、CSS 可读化

 例如

/*------------------------
    每个样式一行
    ---------------------*/ 
li{ 
    background-color:#3399cc; 
    color:#666; 
    font: 1.2em/1.4em Arial, Helvetica, sans-serif; 
    height:300px; 
    margin:10px 5px; 
    padding:5px 0 10px 5px; 
    width:30%; 
    z-index:10; 

 

11、合适的注释。

为css 加上一些注释将会让你的css更清晰易读,方便修改和协同工作。
 

    /*--------------------
        Header
        -----------------*/ 
    #header{ height:145px; position:relative; }  

      
    /*--------------------
        Content
        -----------------*/ 
    #content{ background:#fff; width:650px; float:left; min-height:600px; overflow:hidden;} 

 

 

标签:css
您可能感兴趣