Skip to content

CSS 工程化

概述

现代 CSS 工程化解决样式作用域、复用性、维护性问题。

一、方案对比

方案作用域运行时动态样式类型安全
CSS Modules有限
styled-components
emotion
TailwindBEM有限
CSS Variables

二、CSS Modules

css
/* Button.module.css */
.button {
  padding: 8px 16px;
}
.primary {
  background: blue;
}
jsx
import styles from './Button.module.css';

<button className={`${styles.button} ${styles.primary}`}>
  Click
</button>

// 编译后: button_abc123 primary_def456

三、CSS-in-JS

styled-components

jsx
import styled from 'styled-components';

const Button = styled.button`
  padding: 8px 16px;
  background: ${props => props.primary ? 'blue' : 'gray'};
  
  &:hover {
    opacity: 0.8;
  }
`;

<Button primary>Click</Button>

emotion

jsx
/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';

const buttonStyle = css`
  padding: 8px 16px;
`;

<button css={buttonStyle}>Click</button>

四、Tailwind CSS

html
<button class="px-4 py-2 bg-blue-500 hover:bg-blue-600 rounded">
  Click
</button>

配置

javascript
// tailwind.config.js
module.exports = {
  content: ['./src/**/*.{js,jsx,ts,tsx}'],
  theme: {
    extend: {
      colors: {
        brand: '#ff5500'
      }
    }
  }
};

五、CSS Variables

css
:root {
  --primary: #3b82f6;
  --spacing: 8px;
}

.button {
  background: var(--primary);
  padding: var(--spacing);
}

/* 动态修改 */
document.documentElement.style.setProperty('--primary', '#ff0000');

六、原子化 CSS

javascript
// UnoCSS / Tailwind 原理
const atomicClasses = {
  'p-4': 'padding: 1rem',
  'bg-blue': 'background: blue',
  // 按需生成,无冗余
};

面试高频题

Q1: CSS-in-JS 优缺点?

优点:作用域隔离、动态样式、与组件耦合。缺点:运行时开销、包体积。

Q2: Tailwind vs CSS-in-JS?

Tailwind 无运行时、学习曲线低;CSS-in-JS 更灵活、类型安全。

Q3: CSS Modules 原理?

构建时将类名转换为唯一哈希,实现作用域隔离。

前端面试知识库