隨著專案增長,單一 CSS 文件動輒數千行,尋找某個模組樣式如大海撈針。模組化按「頁面區塊」拆分,讓結構與樣式對應,問題定位從分鐘級降至秒級。
/* ==== Header 區塊 ==== */
.header { display: flex; justify-content: space-between; }
.header__logo { ... }
.header__nav { ... }
/* ==== Main Content 區塊 ==== */
.main { display: grid; grid-template-columns: 1fr 300px; gap: 2rem; }
.content { ... }
.content__article { ... }
/* ==== Sidebar 區塊 ==== */
.sidebar { ... }
.sidebar__widget { ... }
/* ==== Footer 區塊 ==== */
.footer { ... }
.footer__links { ... }
styles/
├── _reset.scss
├── _variables.scss
├── _mixins.scss
├── layout/
│ ├── _header.scss
│ ├── _footer.scss
│ └── _grid.scss
├── components/
│ ├── _button.scss
│ ├── _card.scss
│ └── _modal.scss
├── pages/
│ ├── _home.scss
│ └── _article.scss
└── main.scss /* 統一入口 */
main.scss 按 ITCSS 順序 @forward / @use 各模組,編譯產出單一 main.css,開發時模組獨立,上線合併壓縮。
l- / layout-:佈局層(.l-container)c- / component-:組件層(.c-card)u- / utility-:工具類(.u-mt-16)一眼識別樣式層級,避免跨層級覆蓋。
模組化不是把代碼拆碎,而是建立「結構↔樣式」的清晰映射。從下個專案開始,給 CSS 做個「模組化重構」吧!