Skip to main content

CSS Naming Convention

OOCSS

Object Orinted CSS

主要精神

  • 結構與外觀分離
  • 容器與內容分離

但其實沒有在管你命名規則

.wrapper {
padding: 5px 10px;
}
.panel {
filter: drop-shadow(12px 12px 7px rgba(0, 0, 0, 0.7))
}
.text-bold {
font-weight: bold;
}
.color-red {
colo: red;
}

<div class="container drop-shadow">
<div class="panel">
<label class="text-bold color-red">Show Something</label>
</div>
</div>

SMACSS

Scalable Modular Architecture for CSS

以使用情境分為五類

  • Base
  • Layout 管理佈局
  • Module 模組的基底
  • State 依照狀態改變而疊加的style
  • Theme 整個網站style的改變

Base

全站的設定,例如CSS Reset/Normalize

Example: MeyerWeb CSS Reset

/* http://meyerweb.com/eric/tools/css/reset/ 
v2.0 | 20110126
License: none (public domain)
*/

html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after, q:before, q:after {
content: ''; content: none;
}
table {
border-collapse: collapse; border-spacing: 0;
}

Layout

Grid System, 整體佈局使用的CSS,只出現一次的layout元素該用id而不是class

#container {}

#header {}

#navbar {}
.nav-item {}

#footer {}

Module

可重複利用的component style

.btn {}
.btn-primary {}

State

狀態改變時特有的樣式

.is-enabled {}
.has-error {}

Theme

全站的設定,現在改用CSS Variable使用會容易點 好處是Dark Mode的實現可以直接在這層完成

.theme-bg-color {}
.theme-primary-color {}
.theme-secondary-color {}

BEM

Block 區塊 Element 元素 Modifier 修飾符

與其說是pattern,更像說是css class naming的規則

跟SMACSS對照起來Element-Modifier會對應到Model-State

Block

無底線prefix,可共用的元素

.btn {}
.nav {}

Element

依附在Block下,有兩個底線prefix

.btn__icon {}
.nav__item {}

Modifier

改變Block或Element狀態的style,可以多個

.btn_enabled {}
.nav__item_active {}
.nav__item_active_enabled {}