构建可维护、可扩展的 CSS 代码库
/* Block - 独立的功能块 */
.block {}
/* Element - 块内的元素 */
.block__element {}
/* Modifier - 块或元素的变体 */
.block--modifier {}
.block__element--modifier {}/* 按钮组件 */
.btn {
padding: 10px 20px;
border: 1px solid #ddd;
border-radius: 4px;
}
.btn--primary {
background: #3498db;
color: white;
}
.btn--large {
padding: 15px 30px;
font-size: 16px;
}
/* 卡片组件 */
.card {
border: 1px solid #ddd;
border-radius: 8px;
padding: 20px;
}
.card__title {
font-size: 18px;
font-weight: bold;
margin-bottom: 10px;
}
.card__content {
line-height: 1.6;
}
.card--featured {
border-color: #3498db;
box-shadow: 0 4px 12px rgba(52, 152, 219, 0.1);
}将样式抽象为可重用的对象,强调分离结构和样式。
/* 结构 */
.box {
width: 200px;
height: 200px;
padding: 20px;
}
/* 样式 */
.bg-blue {
background: #3498db;
}
.rounded {
border-radius: 8px;
}将 CSS 分为 5 个类别:
按照特异性从低到高组织 CSS:
.nav {
display: flex;
gap: 20px;
.nav__item {
padding: 10px;
a {
text-decoration: none;
color: #333;
<span class="selector":hover>
color: #3498db;
}
}
}/* 推荐的文件结构 */
/css
/base
- reset.css
- normalize.css
- typography.css
/components
- button.css
- card.css
- nav.css
/layout
- grid.css
- header.css
- footer.css
/utilities
- spacing.css
- colors.css
- typography.css
/themes
- light.css
- dark.css
- main.css /* 主入口文件 */使用 @import 或构建工具实现按需加载:
/* main.css */
@import 'base/reset.css';
@import 'base/typography.css';
@import 'layout/grid.css';
@import 'components/button.css';
@import 'components/card.css';PostCSS 是一个 CSS 处理工具,可以使用插件扩展 CSS 功能。
自动添加浏览器前缀,确保样式在不同浏览器中兼容。
压缩 CSS 文件,减少文件大小,提高加载速度。
| 工具 | 用途 |
|---|---|
| PostCSS | CSS 处理工具 |
| Autoprefixer | 添加浏览器前缀 |
| CSSNano | CSS 压缩 |
| Stylelint | CSS 代码检查 |
| Prettier | 代码格式化 |
/* 导航组件 */
.nav {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px;
background: #f8f9fa;
}
.nav__logo {
font-size: 24px;
font-weight: bold;
color: #3498db;
}
.nav__menu {
display: flex;
gap: 20px;
}
.nav__item {
list-style: none;
}
.nav__link {
text-decoration: none;
color: #333;
transition: color 0.3s ease;
}
.nav__link:hover {
color: #3498db;
}
.nav--fixed {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 1000;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}/* base/reset.css */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* components/button.css */
.btn {
padding: 10px 20px;
border: 1px solid #ddd;
border-radius: 4px;
cursor: pointer;
transition: all 0.3s ease;
}
.btn--primary {
background: #3498db;
color: white;
}
.btn--secondary {
background: #95a5a6;
color: white;
}