CSS2016-04-15
返回首页

CSS 架构方法论

CSS 架构方法论

大型项目需要良好的 CSS 架构。

OOCSS

结构与皮肤分离

/* 结构 */
.btn {
  display: inline-block;
  padding: 10px 20px;
  border-radius: 4px;
}

/* 皮肤 */
.btn-primary {
  background: blue;
  color: white;
}

.btn-danger {
  background: red;
  color: white;
}

容器与内容分离

/* ❌ 依赖容器 */
.sidebar .title {
  font-size: 18px;
}

/* ✅ 独立的类 */
.title-large {
  font-size: 18px;
}

SMACSS

分类

  1. Base - 基础样式
  2. Layout - 布局样式
  3. Module - 模块样式
  4. State - 状态样式
  5. Theme - 主题样式
/* Base */
body {
  font-family: Arial, sans-serif;
}

/* Layout */
.l-header {
  position: fixed;
  top: 0;
}

.l-content {
  margin: 60px auto;
}

/* Module */
.card {
  border: 1px solid #ddd;
}

.card-title {
  font-size: 18px;
}

/* State */
.is-hidden {
  display: none;
}

.is-active {
  font-weight: bold;
}

/* Theme */
.theme-dark .card {
  background: #333;
  color: #fff;
}

BEM

Block Element Modifier

/* Block */
.card {}

/* Element */
.card__header {}
.card__body {}
.card__footer {}

/* Modifier */
.card--featured {}
.card--compact {}
.card__header--large {}
<div class="card card--featured">
  <div class="card__header card__header--large">
    Title
  </div>
  <div class="card__body">
    Content
  </div>
  <div class="card__footer">
    Footer
  </div>
</div>

BEM 最佳实践

/* ❌ 嵌套过深 */
.block__element__subelement {}

/* ✅ 扁平结构 */
.block__element {}
.block__subelement {}

/* ❌ 多个修饰符组合 */
.block--mod1--mod2 {}

/* ✅ 独立修饰符 */
.block--mod1 {}
.block--mod2 {}

ITCSS

倒三角架构

Settings    - 变量、配置
Tools       - Mixins、函数
Generic     - 重置、标准化
Elements    - HTML 元素样式
Objects     - 无装饰模式
Components  - UI 组件
Utilities   - 工具类
/* Settings */
$color-primary: blue;

/* Tools */
@mixin flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* Generic */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* Elements */
h1 {
  font-size: 2rem;
}

/* Objects */
.o-container {
  max-width: 1200px;
  margin: 0 auto;
}

/* Components */
.c-button {
  padding: 10px 20px;
  background: $color-primary;
}

/* Utilities */
.u-hidden {
  display: none !important;
}

方法论选择

方法论 适用场景 学习曲线
OOCSS 灵活的组件系统
SMACSS 大型应用
BEM 团队协作
ITCSS 企业级项目

实践建议

  1. 选择一种方法论 - 不要混合使用
  2. 保持命名一致 - 团队统一规范
  3. 避免深层嵌套 - 最多 3 层
  4. 使用预处理器 - 提高开发效率
  5. 建立组件库 - 可复用的样式组件