组件提取
Tailwind 提倡"组合类"而不是"封装组件",但重复出现的按钮、卡片,总复制一长串类名也难受。Tailwind 提供了提取方式。
方法一:@apply
在 CSS 里用 @apply 把工具类合成为一个自定义类,保留 Tailwind 的语义:
方法二:组件模板
在组件化框架(Vue/React)里,把一段 HTML 抽成组件,类名只在组件里写一次,到处复用。这是实际项目中最常用的方式。
方法三:@layer components
在 @layer components 里定义组件类,优先级介于 base 和 utilities 之间,方便后续覆盖。
代码示例
@layer components {
.btn {
@apply inline-flex items-center justify-center
px-4 py-2 rounded-lg font-medium
transition-colors duration-200;
}
.btn-primary {
@apply bg-green-600 text-white hover:bg-green-700;
}
.btn-outline {
@apply border border-gray-300 text-gray-700 hover:bg-gray-50;
}
}
/* HTML 里直接 <button class="btn btn-primary">按钮</button> */
📚 CSS 属性速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
| 写法 / 语法 | 作用 |
|---|---|
color: #333; | 文字颜色 |
background: #fff; | 背景色 / 背景图 |
font-size: 16px; | 字号 |
font-family: Arial; | 字体 |
font-weight: bold; | 字重(加粗) |
margin: 10px; | 外边距(上右下左) |
padding: 10px; | 内边距 |
border: 1px solid #ccc; | 边框:粗细 样式 颜色 |
border-radius: 8px; | 圆角 |
width: 100%; | 宽度 |
height: 200px; | 高度 |
display: flex; | 弹性布局(现代布局主力) |
display: none; | 隐藏元素 |
position: relative / absolute / fixed; | 定位方式 |
top / left / right / bottom | 定位偏移 |
text-align: center; | 文字水平对齐 |
line-height: 1.6; | 行高 |
overflow: hidden; | 内容溢出处理 |
box-shadow: 0 2px 8px rgba(0,0,0,.1); | 阴影 |
transition: all .3s; | 过渡动画 |
cursor: pointer; | 鼠标手型 |
z-index: 10; | 层叠顺序 |
max-width: 1200px; margin: 0 auto; | 容器居中(经典写法) |
@media (max-width: 768px) {} | 响应式断点 |
:hover | 鼠标悬停状态 |