《Tailwind CSS 移动优先与样式速通:颜色、字体、圆角一次讲透》
作者:@CrabXin 日期:2025-07-23
一、为什么要用移动优先?
手机流量占比已超 60%,移动优先(Mobile-First) 能让页面先在小屏跑通,再逐步增强到大屏,性能与体验双赢。Tailwind CSS 天生就是“默认移动端”,只需从小到大追加断点即可。
二、Tailwind 移动优先 4 步曲
| 步骤 | 做法 | 示例 |
|---|---|---|
| ① 默认样式 | 不加前缀,先写移动端 | text-sm p-4 |
| ② 逐步增强 | 用断点前缀追加样式 | sm:text-base md:text-lg |
| ③ 隐藏/显示 | 按需展示元素 | hidden md:block |
| ④ 任意值 | 需要精确值时 | w-[360px] lg:w-[720px] |
实战 Demo:响应式卡片
<div class="p-4 rounded-lg shadow md:p-6 lg:p-8">
<h2 class="text-lg font-bold md:text-xl lg:text-2xl">响应式卡片</h2>
<p class="text-sm md:text-base">内容随屏宽变化。</p>
</div>
三、颜色迁移:把 bg-purple-500 搬进自定义 CSS
Tailwind 的 bg-purple-500 对应 HEX #a855f7。在 custom.css 中有两种写法:
| 场景 | 代码 |
|---|---|
| 完全脱离 Tailwind | .btn-purple { background-color: #a855f7; } |
| 仍用 Tailwind 调色板 | @layer components { .btn-purple { @apply bg-purple-500; } } |
四、字体、自重、圆角速查表
| 类别 | 类名 | 对应值 |
|---|---|---|
| 字体大小 | text-xs … text-4xl | 12px … 36px |
| 自重 | font-thin … font-black | 100 … 900 |
| 圆角 | rounded-sm … rounded-full | 2px … 50% |
| 任意值 | text-[15px] rounded-[10px] | 自定义 |
组合示例:按钮三态
<button class="px-4 py-2 text-sm font-medium rounded-md
sm:px-6 sm:py-3 sm:text-base sm:font-semibold sm:rounded-lg
hover:bg-purple-600 active:scale-95">
立即体验
</button>
五、30 秒速记口诀
“默认移动端,前缀逐级加;字体自重圆角,类名即答案。”
六、延伸阅读
把这篇博客收藏起来,下次写响应式页面,直接抄类名即可!