樣式表的基本結構如下:
[selector] {
[property]: [value]; /* <- 一條宣告 */
}
- 連接(BEM 命名法例外).widget {
padding: 10px;
border: 1px solid #BADA55;
background-color: #C0FFEE;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.widget-heading {
font-size: 1.5rem;
line-height: 1;
font-weight: bold;
color: #BADA55;
margin-right: -10px;
margin-left: -10px;
padding: 0.25em;
}
這裡有兩件事值得注意。
第一,.widget-heading 比 .widget 多縮排一級,因為它是後者的子元素。這樣閱讀程式碼時,DOM 的層級關係一眼就能掌握,不必來回對照 HTML。
第二,.widget-heading 的宣告順序是依相關性排列的:它是行內級元素,所以先寫字體相關的屬性,再處理間距與邊距。
另外,前綴宣告的縮排對齊,讓 -webkit-、-moz- 與標準屬性的值在視覺上排成一列,比對時不容易看錯。
並非所有情況都適合拆開。當一堆規則結構單純、彼此高度相似時,單行反而更緊湊易讀:
.t10 { width: 10% }
.t20 { width: 20% }
.t25 { width: 25% } /* 1/4 */
.t30 { width: 30% }
.t33 { width: 33.333% } /* 1/3 */
.t40 { width: 40% }
.t50 { width: 50% } /* 1/2 */
.t60 { width: 60% }
.t66 { width: 66.666% } /* 2/3 */
.t70 { width: 70% }
.t75 { width: 75% } /* 3/4 */
.t80 { width: 80% }
.t90 { width: 90% }
這個例子取自 Inuit.css 的表格網格系統。當每條規則只有一個屬性、且整組規則語義一致時,單行寫法讓對照與修改都更快。
判斷標準其實很實用:規則內部有兩三個以上屬性、或值本身很長,就拆行;同質且短小的規則群,就壓縮。格式的最終目的是降低閱讀成本,而不是形式上的統一。