CSS 命名和架构方案有哪些?BEM、CSS Modules、CSS-in-JS、Tailwind 的优缺点?

1. BEM(Block Element Modifier)

/* 块__元素--修饰符 */
.card { }
.card__title { }
.card__body { }
.card--featured { }
.card__title--large { }

2. CSS Modules

/* Button.module.css */
.button { background: blue; }
.active { background: red; }
import styles from './Button.module.css'
<button className={styles.button}>Click</button>

3. CSS-in-JS(styled-components / Emotion)

const Button = styled.button`
  background: ${props => props.primary ? 'blue' : 'gray'};
  padding: 8px 16px;
`
<Button primary>Click</Button>

4. Tailwind CSS(原子化 CSS)

<button class="bg-blue-500 hover:bg-blue-700 text-white px-4 py-2 rounded">
  Click
</button>

5. Scoped CSS(Vue)

<style scoped>
.button { background: blue; }
</style>

对比总结

方案 隔离性 动态样式 开发速度 包体积 适合场景
BEM 依赖命名 ❌ 中 小 传统项目
CSS Modules ✅ 编译时 ❌ 快 小 React 项目
CSS-in-JS ✅ 运行时 ✅ 快 大 动态主题
Tailwind ❌ ❌ 最快 最小 快速开发
Scoped ✅ ❌ 快 小 Vue 项目

选择建议

同分类其他题目