蓝色天空网mbsky.com · 知识 · 实践 · 创造Tailwind CSS · 本地阅读预览
教程 / 前端开发 / Tailwind CSS

Tailwind CSS 基础概念

全面梳理 Tailwind CSS 15 项基础概念(工具类、响应式、颜色尺寸、间距、Flex/Grid 布局、边框、状态、可见性、自定义配置、暗色、插件与指令),全部经离线 Chromium 实测核对。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

基础概念总览与排版颜色间距

Tailwind CSS 通过一套高度可定制的原子工具类体系覆盖界面构建全流程。下表先汇总 15 个核心概念的职责边界,随后结合逐项实例与离线 Chromium 计算样式展开核对。

概念详解第一项是工具类优先(Utility-First):直接在元素上写 `text-center text-blue-500 font-bold`,无需额外 CSS 文件即可完成居中、蓝色文字与加粗。本站 Chromium 实测其计算值为 `textAlign: center`、`color: rgb(59, 130, 246)`、`fontWeight: 700`。

第三、四、六项分别聚焦颜色与尺寸、间距及文本样式:`text-lg text-gray-600` 在 Chromium 中实测为 `18px` 与 `rgb(75, 85, 99)`;间距类 `p-4 m-8` 对应 `1rem`(`16px`)内边距与 `2rem`(`32px`)外边距;文本组合 `text-center font-semibold text-red-500` 实测为 `fontWeight: 600` 与 `rgb(239, 68, 68)`。

响应式前缀、可见性、布局与尺寸栅格

第二项响应式前缀与第十项可见性均遵循移动优先原则。对 `bg-red-500 sm:bg-green-500 md:bg-blue-500 lg:bg-yellow-500` 及 `invisible sm:visible` 跨视口实测:`500px` 下背景为红色 `rgb(239, 68, 68)` 且 `visibility: hidden`;达到 `640px`(`sm:`)切为绿色 `rgb(34, 197, 94)` 与 `visible`;达到 `768px`(`md:`)切为蓝色 `rgb(59, 130, 246)`;达到 `1024px`(`lg:`)切为黄色 `rgb(234, 179, 8)`。

第五项布局、第九项尺寸与第十一项栅格系统共同承担页面骨架:`flex justify-between items-center` 实测为 `display: flex`、`justifyContent: space-between`、`alignItems: center`;`grid grid-cols-3 gap-4` 与 `gap-2` 分别产出 3 等分轨道、`16px` 与 `8px` 列间距,其中 `col-span-2` 在 `332px` 宽(`16px` 间距)网格中精确占据 `216px`(单列 `100px`);尺寸组合 `w-64 h-32 bg-gray-300` 实测盒尺寸精确为 `256px × 128px`。

背景边框、交互状态与框架扩展机制

第七项背景和边框与第八项悬停状态负责视觉层次与反馈:`bg-yellow-200 border border-gray-400` 实测背景 `rgb(254, 240, 138)`、边框宽度 `1px` 与边框色 `rgb(156, 163, 175)`;按钮 `bg-blue-500 hover:bg-blue-700 text-white` 默认背景为 `rgb(59, 130, 246)`,在 Chromium 真实执行 `hover()` 后切换为 `rgb(29, 78, 216)`。

第十二至十五项展示 Tailwind 的四大扩展与组织能力:在 `tailwind.config.js` 的 `theme.extend.colors` 中注册 `primary: '#1D4ED8'` 后,`bg-primary` 实测为 `rgb(29, 78, 216)`;暗色模式类 `bg-white dark:bg-black text-black dark:text-white` 在根元素添加 `dark` 类后背景与文字精确反转;自定义插件通过 `addUtilities` 注册 `.rotate-45` 在 Chromium 测得变换矩阵 `matrix(0.707107, 0.707107, -0.707107, 0.707107, 0, 0)`;而在样式入口通过 `@tailwind base/components/utilities`(对应 CSS `@layer`)统一编排基础、组件与工具三层样式。

Tailwind CSS 15 项基础概念速查表

概念说明
工具类 (Utility-First)核心设计方法,直接将单一职责的工具类组合到 HTML 元素上。
响应式前缀利用 sm:、md:、lg:、xl: 等移动优先断点前缀按视口宽度应用样式。
颜色和尺寸内置分级调色板(如 bg-red-500)与排版尺度(如 text-lg)便于快速复用。
间距 (Spacing)通过 p-、m-、pt-、pr- 等比例类统一管理内外边距。
布局 (Layout)提供 flex、grid、float 等类快速控制容器排布方式。
文本样式涵盖对齐、字重、颜色与大小写转换(如 text-center、font-bold、uppercase)。
背景和边框设置背景色、背景图、边框线宽与颜色(如 bg-gray-200、border-red-500)。
悬停和状态借助 hover:、focus:、active: 等状态修饰符响应用户交互。
尺寸 (Sizing)使用 w-、h- 家族控制元素宽高(如 w-64 为 256px、h-screen 为 100vh)。
可见性 (Visibility)用 visible 与 invisible 控制元素视觉可见性并保留占位空间。
栅格系统 (Grid System)基于 CSS Grid 提供 grid、grid-cols-3、col-span-2 等多列网格工具类。
自定义配置在配置文件(v3 为 tailwind.config.js,v4 支持 @theme)定制颜色、间距与字体。
暗色模式 (Dark Mode)通过 dark: 前缀配合类切换或系统偏好声明深色主题样式。
插件 (Plugins)利用官方或自定义插件调用 addUtilities 等 API 扩展框架能力。
指令 (Directives)在 CSS 文件中通过 @tailwind(v3)或 @import(v4)引入 base、components、utilities 层。

离线 Chromium 核验 15 项基础概念(排版/响应式/布局/状态/暗色/插件)

python · 阅读源码
"""Offline Playwright Chromium lab for Tailwind CSS Ch 06 (basic)."""
import json
import os
from playwright.sync_api import sync_playwright

TW_CSS = """
@layer base, components, utilities;
@layer base {
  *, *::before, *::after { box-sizing: border-box; }
  body { margin: 0; font-family: system-ui, sans-serif; font-size: 16px; }
  p { margin: 0; }
}
@layer utilities {
  .text-center { text-align: center; }
  .text-blue-500 { color: #3b82f6; }
  .text-gray-600 { color: #4b5563; }
  .text-red-500 { color: #ef4444; }
  .text-white { color: #ffffff; }
  .text-black { color: #000000; }
  .text-lg { font-size: 1.125rem; line-height: 1.75rem; }
  .font-bold { font-weight: 700; }
  .font-semibold { font-weight: 600; }
  .p-4 { padding: 1rem; }
  .m-8 { margin: 2rem; }
  .bg-red-500 { background-color: #ef4444; }
  .bg-yellow-200 { background-color: #fef08a; }
  .bg-blue-500 { background-color: #3b82f6; }
  .bg-gray-300 { background-color: #d1d5db; }
  .bg-white { background-color: #ffffff; }
  .bg-primary { background-color: #1d4ed8; }
  .border { border-width: 1px; border-style: solid; }
  .border-gray-400 { border-color: #9ca3af; }
  .hover\\:bg-blue-700:hover { background-color: #1d4ed8; }
  .flex { display: flex; }
  .justify-between { justify-content: space-between; }
  .items-center { align-items: center; }
  .grid { display: grid; }
  .grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
  .col-span-2 { grid-column: span 2 / span 2; }
  .gap-4 { gap: 1rem; }
  .gap-2 { gap: 0.5rem; }
  .w-64 { width: 16rem; }
  .h-32 { height: 8rem; }
  .invisible { visibility: hidden; }
  .rotate-45 { transform: rotate(45deg); }
  .dark .dark\\:bg-black { background-color: #000000; }
  .dark .dark\\:text-white { color: #ffffff; }
  @media (min-width: 640px) {
    .sm\\:bg-green-500 { background-color: #22c55e; }
    .sm\\:visible { visibility: visible; }
  }
  @media (min-width: 768px) {
    .md\\:bg-blue-500 { background-color: #3b82f6; }
  }
  @media (min-width: 1024px) {
    .lg\\:bg-yellow-500 { background-color: #eab308; }
  }
}
"""


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": 500, "height": 600})

        # Case 1: Utility-first text, color, sizing, spacing
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
  <div id="u1" class="text-center text-blue-500 font-bold">Tailwind Utility Classes</div>
  <p id="u3" class="text-lg text-gray-600">Text with pre-defined size and color</p>
  <div id="u4" class="p-4 m-8">Padding and Margin Example</div>
  <p id="u6" class="text-center font-semibold text-red-500">Centered Bold Text</p>
</body></html>""")
        actual1 = page.evaluate("""() => {
            const s1 = getComputedStyle(document.getElementById('u1'));
            const s3 = getComputedStyle(document.getElementById('u3'));
            const s4 = getComputedStyle(document.getElementById('u4'));
            const s6 = getComputedStyle(document.getElementById('u6'));
            return {
                u1Align: s1.textAlign, u1Color: s1.color, u1Weight: s1.fontWeight,
                u3Size: s3.fontSize, u3Color: s3.color,
                u4Padding: s4.padding, u4Margin: s4.margin,
                u6Weight: s6.fontWeight, u6Color: s6.color,
            };
        }""")
        expected1 = {
            "u1Align": "center", "u1Color": "rgb(59, 130, 246)", "u1Weight": "700",
            "u3Size": "18px", "u3Color": "rgb(75, 85, 99)",
            "u4Padding": "16px", "u4Margin": "32px",
            "u6Weight": "600", "u6Color": "rgb(239, 68, 68)",
        }
        cases.append(dict(
            name="utility_text_color_spacing",
            expected=expected1,
            actual=actual1,
            passed=(actual1 == expected1),
        ))

        # Case 2: Responsive prefixes (sm/md/lg) & visibility (invisible sm:visible)
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
  <div id="resp" class="bg-red-500 sm:bg-green-500 md:bg-blue-500 lg:bg-yellow-500">Responsive</div>
  <div id="vis" class="invisible sm:visible">Visible on sm+</div>
</body></html>""")
        snap = {}
        for w in (500, 640, 768, 1024):
            page.set_viewport_size({"width": w, "height": 600})
            snap[f"w{w}"] = page.evaluate("""() => ({
                bg: getComputedStyle(document.getElementById('resp')).backgroundColor,
                vis: getComputedStyle(document.getElementById('vis')).visibility,
            })""")
        expected2 = {
            "w500": {"bg": "rgb(239, 68, 68)", "vis": "hidden"},
            "w640": {"bg": "rgb(34, 197, 94)", "vis": "visible"},
            "w768": {"bg": "rgb(59, 130, 246)", "vis": "visible"},
            "w1024": {"bg": "rgb(234, 179, 8)", "vis": "visible"},
        }
        cases.append(dict(
            name="responsive_prefix_and_visibility",
            expected=expected2,
            actual=snap,
            passed=(snap == expected2),
        ))

        # Case 3: Flex, Grid (gap-4, gap-2, col-span-2) & Sizing (w-64 h-32)
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
  <div id="flx" class="flex justify-between items-center" style="width:300px">
    <div id="fa">Item 1</div><div id="fb">Item 2</div>
  </div>
  <div id="grd" class="grid grid-cols-3 gap-4" style="width:332px">
    <div class="col-span-2" id="gc1">1</div><div id="gc2">2</div>
  </div>
  <div id="grd2" class="grid grid-cols-3 gap-2" style="width:316px">
    <div>1</div><div>2</div><div>3</div>
  </div>
  <div id="sz" class="w-64 h-32 bg-gray-300">Width and Height</div>
</body></html>""")
        actual3 = page.evaluate("""() => {
            const fs = getComputedStyle(document.getElementById('flx'));
            const gs = getComputedStyle(document.getElementById('grd'));
            const g2s = getComputedStyle(document.getElementById('grd2'));
            const szRect = document.getElementById('sz').getBoundingClientRect();
            const c1Rect = document.getElementById('gc1').getBoundingClientRect();
            const c2Rect = document.getElementById('gc2').getBoundingClientRect();
            return {
                flexDisplay: fs.display,
                flexJustify: fs.justifyContent,
                flexAlign: fs.alignItems,
                gridCols: gs.gridTemplateColumns.split(' ').length,
                gridGap: gs.columnGap,
                grid2Gap: g2s.columnGap,
                span2Width: Math.round(c1Rect.width),
                span1Width: Math.round(c2Rect.width),
                boxWidth: Math.round(szRect.width),
                boxHeight: Math.round(szRect.height),
            };
        }""")
        expected3 = {
            "flexDisplay": "flex",
            "flexJustify": "space-between",
            "flexAlign": "center",
            "gridCols": 3,
            "gridGap": "16px",
            "grid2Gap": "8px",
            "span2Width": 216,
            "span1Width": 100,
            "boxWidth": 256,
            "boxHeight": 128,
        }
        cases.append(dict(
            name="layout_flex_grid_and_sizing",
            expected=expected3,
            actual=actual3,
            passed=(actual3 == expected3),
        ))

        # Case 4: Background, Border & Hover interactive state
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
  <div id="bb" class="bg-yellow-200 border border-gray-400">Box</div>
  <button id="hb" class="bg-blue-500 hover:bg-blue-700 text-white">Hover Me</button>
</body></html>""")
        before_hover = page.eval_on_selector("#hb", "el => getComputedStyle(el).backgroundColor")
        page.hover("#hb")
        after_hover = page.eval_on_selector("#hb", "el => getComputedStyle(el).backgroundColor")
        bb_info = page.eval_on_selector("#bb", """el => {
            const s = getComputedStyle(el);
            return { bg: s.backgroundColor, borderWidth: s.borderTopWidth, borderColor: s.borderTopColor };
        }""")
        actual4 = {
            "boxBg": bb_info["bg"],
            "boxBorderWidth": bb_info["borderWidth"],
            "boxBorderColor": bb_info["borderColor"],
            "btnDefaultBg": before_hover,
            "btnHoverBg": after_hover,
        }
        expected4 = {
            "boxBg": "rgb(254, 240, 138)",
            "boxBorderWidth": "1px",
            "boxBorderColor": "rgb(156, 163, 175)",
            "btnDefaultBg": "rgb(59, 130, 246)",
            "btnHoverBg": "rgb(29, 78, 216)",
        }
        cases.append(dict(
            name="background_border_and_hover_state",
            expected=expected4,
            actual=actual4,
            passed=(actual4 == expected4),
        ))

        # Case 5: Custom theme color, Dark mode toggle, Plugin .rotate-45, @layer directives
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
  <div id="pri" class="bg-primary text-white">Primary</div>
  <div id="dm" class="bg-white dark:bg-black text-black dark:text-white">Dark Mode</div>
  <div id="rot" class="rotate-45" style="width:40px;height:40px">R</div>
</body></html>""")
        light_dm = page.eval_on_selector("#dm", "el => ({ bg: getComputedStyle(el).backgroundColor, fg: getComputedStyle(el).color })")
        page.evaluate("document.documentElement.classList.add('dark')")
        dark_dm = page.eval_on_selector("#dm", "el => ({ bg: getComputedStyle(el).backgroundColor, fg: getComputedStyle(el).color })")
        rot_matrix = page.eval_on_selector("#rot", "el => getComputedStyle(el).transform")
        pri_bg = page.eval_on_selector("#pri", "el => getComputedStyle(el).backgroundColor")
        actual5 = {
            "primaryBg": pri_bg,
            "lightBg": light_dm["bg"],
            "lightColor": light_dm["fg"],
            "darkBg": dark_dm["bg"],
            "darkColor": dark_dm["fg"],
            "rotate45Matrix": rot_matrix,
        }
        expected5 = {
            "primaryBg": "rgb(29, 78, 216)",
            "lightBg": "rgb(255, 255, 255)",
            "lightColor": "rgb(0, 0, 0)",
            "darkBg": "rgb(0, 0, 0)",
            "darkColor": "rgb(255, 255, 255)",
            "rotate45Matrix": "matrix(0.707107, 0.707107, -0.707107, 0.707107, 0, 0)",
        }
        cases.append(dict(
            name="custom_theme_dark_plugin_directives",
            expected=expected5,
            actual=actual5,
            passed=(actual5 == expected5),
        ))

        browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    run()
预期结果 · 待实际运行核验
  • 核对 500px-1024px 四段响应式颜色与可见性、3 列网格 col-span-2(216px vs 100px)、w-64/h-32(256x128px)、hover 切色、暗色反转与 rotate-45 变换矩阵。
离线 Chromium 核验 15 项基础概念(排版/响应式/布局/状态/暗色/插件)

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:4af3775d7a261d56778950023506611d02926eb7369a49215a49212f62164927

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Tailwind CSS 基础概念实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:639771dcb261305600dff5d81c6864e22726eef0de5adf878c63337545d2fc09

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

`invisible` 与 `hidden` 在控制元素显示隐藏时对页面布局占位有何本质区别?

展开参考解答

`invisible` 对应 `visibility: hidden`,元素虽不可见但仍保留原始盒模型占位;`hidden` 对应 `display: none`,元素会从文档流布局中彻底移除不占空间。

规范与官方依据