Tailwind CSS 教程
核对 Tailwind CSS 实用优先定位、前置知识基础,以及离线 Chromium 实测的工具类卡片计算样式与盒模型几何表现。
学完这一章,你能够
- 核对 Tailwind CSS 实用优先定位、前置知识基础,以及离线 Chromium 实测的工具类卡片计算样式与盒模型几何表现。
Tailwind CSS 定位与核心设计思路
Tailwind CSS 是一款开源、实用类优先(Utility-First)的 CSS 框架,由 Adam Wathan 与 Jonathan Reinink 于 2017 年启动开发并在 2018 年正式推出。它不强制捆绑固定的组件外观,而是提供大量粒度细、语义单一的工具类,允许开发者直接在 HTML 标签上组合出定制界面。
本教程面向具备基础 Web 排版经验的学习者:只要熟悉常见 HTML 标签与 CSS 盒模型、颜色和布局属性,即可循序渐进掌握 Tailwind CSS 并在实际前端项目中独立搭建界面。
开始系统学习前,建议先具备 HTML、CSS 与 JavaScript 的基础语法能力;若计划在本地工程中通过构建工具编译样式,还应了解 Node.js 与包管理命令的基本用法。
工具类入门实例与离线 Chromium 实测
最直观的起步示例是为一个 `<div>` 同时附加 `bg-blue-500 text-white p-4 rounded-lg` 四个工具类:无需新建自定义 CSS 选择器,即可快速得到蓝底白字、带内边距和圆角的卡片。本站离线 Chromium 实测该卡片渲染结果:`backgroundColor` 为 `rgb(59, 130, 246)`、`color` 为 `rgb(255, 255, 255)`、`padding` 为 `16px`、`borderRadius` 为 `8px`;将 `w-80`(`320px` 宽)卡片由 `p-4`(`16px`)切换为 `p-6`(`24px`)时,总高度精确增加 `16px`,而仅靠 `bg-emerald-500 px-4 py-2 rounded-md` 或 `bg-slate-100 border border-slate-300 rounded-xl` 就能零自定义 CSS 拼出完全不同的按钮与提示面板。
日常查阅工具类映射、主题变量与版本迁移指南时,可直接参考 Tailwind CSS 官方网站(https://tailwindcss.com/)与官方技术文档(https://tailwindcss.com/docs/)。
离线 Chromium 核验 Tailwind CSS 入门卡片计算样式与盒模型几何
"""Offline Playwright Chromium lab for Tailwind CSS Ch 01 (tutorial)."""
import json
import os
from playwright.sync_api import sync_playwright
TW_CSS = """
*, *::before, *::after { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, -apple-system, sans-serif; font-size: 16px; line-height: 1.5; }
.bg-blue-500 { background-color: #3b82f6; }
.bg-emerald-500 { background-color: #10b981; }
.bg-slate-100 { background-color: #f1f5f9; }
.text-white { color: #ffffff; }
.text-slate-800 { color: #1e293b; }
.p-4 { padding: 1rem; }
.p-6 { padding: 1.5rem; }
.px-4 { padding-left: 1rem; padding-right: 1rem; }
.py-2 { padding-top: 0.5rem; padding-bottom: 0.5rem; }
.rounded-md { border-radius: 0.375rem; }
.rounded-lg { border-radius: 0.5rem; }
.rounded-xl { border-radius: 0.75rem; }
.border { border-width: 1px; border-style: solid; }
.border-slate-300 { border-color: #cbd5e1; }
.w-80 { width: 20rem; }
"""
def launch_browser(p):
exe = p.chromium.executable_path
if exe and os.path.exists(exe):
return p.chromium.launch(headless=True)
for ch in ("chrome", "msedge"):
try:
return p.chromium.launch(channel=ch, headless=True)
except Exception:
continue
return p.chromium.launch(headless=True)
def run():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page(viewport={"width": 1024, "height": 768})
# Case 1: Official tutorial hero card utility styles
page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
<div id="hero" class="bg-blue-500 text-white p-4 rounded-lg">
Hello, Tailwind CSS!
</div>
</body></html>""")
actual1 = page.eval_on_selector("#hero", """el => {
const s = getComputedStyle(el);
return {
text: el.textContent.trim(),
backgroundColor: s.backgroundColor,
color: s.color,
padding: s.padding,
borderRadius: s.borderRadius,
};
}""")
expected1 = {
"text": "Hello, Tailwind CSS!",
"backgroundColor": "rgb(59, 130, 246)",
"color": "rgb(255, 255, 255)",
"padding": "16px",
"borderRadius": "8px",
}
cases.append(dict(
name="hero_card_utility_styles",
expected=expected1,
actual=actual1,
passed=(actual1 == expected1),
))
# Case 2: Box geometry under p-4 vs p-6 with fixed w-80 (320px)
page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
<div id="card-a" class="w-80 bg-blue-500 text-white p-4 rounded-lg">Line</div>
<div id="card-b" class="w-80 bg-blue-500 text-white p-6 rounded-lg">Line</div>
</body></html>""")
actual2 = page.evaluate("""() => {
const a = document.getElementById('card-a');
const b = document.getElementById('card-b');
const ra = a.getBoundingClientRect();
const rb = b.getBoundingClientRect();
return {
widthA: Math.round(ra.width),
widthB: Math.round(rb.width),
paddingA: getComputedStyle(a).paddingTop,
paddingB: getComputedStyle(b).paddingTop,
heightDeltaPx: Math.round(rb.height - ra.height),
};
}""")
expected2 = {
"widthA": 320,
"widthB": 320,
"paddingA": "16px",
"paddingB": "24px",
"heightDeltaPx": 16,
}
cases.append(dict(
name="utility_composition_box_geometry",
expected=expected2,
actual=actual2,
passed=(actual2 == expected2),
))
# Case 3: Distinct custom UI cards without custom semantic CSS
page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
<button id="btn" class="bg-emerald-500 text-white px-4 py-2 rounded-md">Start</button>
<div id="panel" class="bg-slate-100 text-slate-800 border border-slate-300 p-4 rounded-xl">Notice</div>
</body></html>""")
actual3 = page.evaluate("""() => {
const bs = getComputedStyle(document.getElementById('btn'));
const ps = getComputedStyle(document.getElementById('panel'));
return {
btnBg: bs.backgroundColor,
btnPadX: bs.paddingLeft,
btnPadY: bs.paddingTop,
btnRadius: bs.borderRadius,
panelBg: ps.backgroundColor,
panelColor: ps.color,
panelBorderWidth: ps.borderTopWidth,
panelBorderColor: ps.borderTopColor,
panelRadius: ps.borderRadius,
};
}""")
expected3 = {
"btnBg": "rgb(16, 185, 129)",
"btnPadX": "16px",
"btnPadY": "8px",
"btnRadius": "6px",
"panelBg": "rgb(241, 245, 249)",
"panelColor": "rgb(30, 41, 59)",
"panelBorderWidth": "1px",
"panelBorderColor": "rgb(203, 213, 225)",
"panelRadius": "12px",
}
cases.append(dict(
name="zero_custom_css_card_variants",
expected=expected3,
actual=actual3,
passed=(actual3 == expected3),
))
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
run()
- 核对 bg-blue-500/text-white/p-4/rounded-lg 计算为 rgb(59,130,246)、rgb(255,255,255)、16px、8px,p-4 切换 p-6 高度增量 16px,以及零自定义 CSS 按钮/面板渲染。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:ec7630e623464755700b70168b4f0f839d3a5260f355134fcc2aa6a672b745a8
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:c5992439fd353a9f7ee30957370764caf7f229a986867bf75e9369e2e194bebc
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么在 `w-80`(`border-box`)卡片上把 `p-4` 改为 `p-6` 时,元素宽度仍保持 `320px` 而高度增加了 `16px`?
展开参考解答
`box-sizing: border-box` 使显式指定的宽度包含内边距,因此宽度维持 `320px`;而高度随内容自适应,上下内边距各从 `16px` 增至 `24px`,合计增高 `16px`。