DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> DIV十CSS布局 >> 布局實例
CSS 優化 12 式:寫出更有效率也更好維護的樣式
編輯:布局實例     

寫得好的 CSS 能實際提升頁面渲染速度。原理很直白:瀏覽器需要解析的規則越少,樣式計算就越快。MDN 把選擇器分成四大類,效率由高到低依序是:

  1. ID 規則
  2. Class 規則
  3. 標籤規則
  4. 通用規則(*)

關於效率的系統性討論,最早可回溯到 Steve Souders 在 2009 年出版的《高性能網站建設進階指南》,Google 的《高效 CSS 選擇器的最佳實踐》也有更細節的說明。以下整理 12 個實用原則。

一、避免過度約束

不要加上不必要的標籤或 class 限定。

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

二、後代選擇器最傷效能

除了效能差,它還很脆弱:HTML 與 CSS 高度耦合,結構一動樣式就得跟著改。在大團隊裡寫 HTML 和 CSS 的往往不是同一個人,這個問題會被放大。

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

三、避免鏈式(交集)選擇器

情況和過度約束類似,更明智的做法是開一個語意清楚的新 class。

/* 糟糕 */ .menu.left.icon {..}
/* 好的 */ .menu-left-icon {..}

四、貫徹 KISS 原則

假設有這樣的 DOM:

<ul id="navigator">
  <li><a href="#" class="twitter">Twitter</a></li>
  <li><a href="#" class="facebook">Facebook</a></li>
  <li><a href="#" class="dribble">Dribbble</a></li>
</ul>
/* 糟糕 */ #navigator li a {..}
/* 好的 */ #navigator {..}

五、使用複合(緊湊)語法

/* 糟糕 */
.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 table tr.otherclass td.somerule {..}
/* 好的 */ .someclass .otherclass td.somerule {..}

七、避免重複宣告

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

八、進一步精簡規則

在上一步的基礎上,把不同 class 間重複的宣告抽調出來,只留下有差異的部分。

/* 好的 */
.someclass, .otherclass {
  color: red; background: blue; height: 150px; width: 150px;
}
.someclass  { font-size: 16px; }
.otherclass { font-size: 8px; }

九、別用含糊的命名

好的 class 名應該描述「它是什麼」,而不是「它長什麼樣」。.red-text 在換色當天就會變成一個笑話,.alert-text 才能活得長久。

十、避開 !important

如果非得靠 !important 才能壓過某條規則,通常代表選擇器的優先權設計出了問題。回頭調整結構會更好。

十一、遵循固定的宣告順序

.someclass {
  /* Positioning */
  /* Display & Box Model */
  /* Background and typography styles */
  /* Transitions */
  /* Other */
}

十二、把格式排整齊

可讀性和可維護性成正比。

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

這裡只涵蓋了其中一小部分規則,都是實務上最容易見效的幾條。想深入閱讀,可以參考 MDN 的〈編寫高效的 CSS〉與 Google 的〈優化瀏覽器渲染指南〉。

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