DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> DIV十CSS布局 >> 布局實例
CSS 撰寫規範:五個讓樣式表更乾淨的原則
編輯:布局實例     

一、避免过度约束

一般原則是:不要加上不必要的約束。

/* 糟糕 */
ul#someid   { ... }
.menu#otherid { ... }

/* 好的 */
#someid   { ... }
#otherid  { ... }

二、後代選擇符最糟

後代選擇符不僅效能低落,程式碼也很脆弱:HTML 結構一改,CSS 就得跟著動。在大團隊裡,寫 HTML 和寫 CSS 的往往不是同一個人,這種耦合會變成協作夢魘。

/* 爛透了 */
html div tr td { ... }

三、盡可能使用複合語法

/* 糟糕 */
.someclass {
  padding-top: 20px;
  padding-bottom: 20px;
  padding-left: 10px;
  padding-right: 10px;
  background: #000;
  background-image: url(../imgs/carrot.png);
  background-position: bottom;
  background-repeat: repeat-x;
}

/* 好的 */
.someclass {
  padding: 20px 10px;
  background: #000 url(../imgs/carrot.png) repeat-x bottom;
}

複合語法不僅字數少,也讓「這組屬性屬於同一件事」的意圖更清楚。

四、避免不必要的重複

/* 糟糕 */
.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;
}

五、把格式整理好

程式碼的可讀性與可維護性成正比。多選擇器時每個一行:

/* 糟糕 */
.someclass-a, .someclass-b, .someclass-c, .someclass-d {
  ...
}

/* 好的 */
.someclass-a,
.someclass-b,
.someclass-c,
.someclass-d {
  ...
}

屬性值很長時同樣換行對齊,讓結構一目了然:

/* 好的做法 */
.someclass {
  background-image:
    linear-gradient(#000, #ccc),
    linear-gradient(#ccc, #ddd);
  box-shadow:
    2px 2px 2px #000,
    1px 4px 1px 1px #ddd inset;
}

這些規則看似瑣碎,但在一個數千行的樣式表中,它們決定了三個月後你(或你的同事)是否還看得懂自己在寫什麼。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved