TailwindCSS 初探
一、背景
最近在做前端页面的时候,发现自己写 CSS 越来越懒,总是想有没有一种方式,直接在 HTML 里就能把样式搞定,不用来回切 CSS 文件。
于是就试了试 TailwindCSS ,一个原子化 CSS 框架,简单来说,就是帮你把常用的样式拆成一个个小类名,你只要在标签上堆这些类,就能快速完成页面布局和样式。
它的特点:
- 不用写 CSS 文件(大部分情况)
- 类名固定,不会冲突
- 设计系统化,颜色、间距、字体都可以统一配置
- 构建时自动清理没用的样式,最终产物很小
二、常用语法
Tailwind 的类名基本是 功能 + 值 的组合,比如 bg-blue-500
表示背景色是蓝色 500 号,p-4
表示 padding 为 1rem。
常用的可以分几类:
1. 布局类
css
<div class="flex justify-center items-center">
<p>居中内容</p>
</div>
flex
:开启 Flex 布局justify-center
:水平居中items-center
:垂直居中
2. 间距类
css
<div class="p-4 m-2">
<p>有内外边距的盒子</p>
</div>
p-4
:padding 全方向 1remm-2
:margin 全方向 0.5rem
3. 颜色类
ini
<button class="bg-blue-500 text-white">
提交
</button>
bg-blue-500
:背景色蓝色 500text-white
:文字颜色白色
4. 字体类
css
<p class="text-lg font-bold">
大号加粗文字
</p>
text-lg
:字体大小大号font-bold
:加粗
5. 圆角与边框
css
<img class="rounded-full border border-gray-300" src="avatar.png" />
rounded-full
:圆形border
:有边框border-gray-300
:边框颜色灰色 300
6. 变量与复用:@apply
虽然 Tailwind 鼓励直接在 HTML 写类,但有时候我们想复用一组样式,可以用 @apply
在 CSS 中组合原子类:
less
/* styles.css */
.btn-primary {
@apply bg-blue-500 text-white px-4 py-2 rounded;
}
.btn-secondary {
@apply bg-gray-500 text-white px-4 py-2 rounded;
}
然后在 HTML 中:
ini
<button class="btn-primary">提交</button>
<button class="btn-secondary">取消</button>
这样就能在保留 Tailwind 优势的同时,让类名更简洁。
7. 配置变量(tailwind.config.js)
Tailwind 的颜色、间距等都可以在 tailwind.config.js
中统一配置,比如:
css
module.exports = {
theme: {
extend: {
colors: {
brand: '#ff6600',
},
},
},
};
然后就能用:
ini
<div class="bg-brand text-white">品牌色背景</div>
三、结语
TailwindCSS 用起来很轻松,尤其是做原型、个人项目、小型后台的时候,几乎不用写额外的 CSS 文件,直接在 HTML/JSX 里堆类就能搞定布局和样式。
当然,大型项目最好配合组件封装、@apply
、统一配置等方式来保持可维护性。