蓝色天空.知识 · 实践 · 创造
我的收藏
Tailwind CSS 教程目录 24章
Tailwind CSS / LEARN BY DOING

Tailwind CSS 安装(CDN)

核对官方 Play CDN 与 jsDelivr 静态 CSS 引入差异、行内 tailwind.config 扩展、type=text/tailwindcss 自定义层及插件参数用法。

学完这一章,你能够

  • 核对官方 Play CDN 与 jsDelivr 静态 CSS 引入差异、行内 tailwind.config 扩展、type=text/tailwindcss 自定义层及插件参数用法。

两种 CDN 引入方式与适用边界

若只需在单页 HTML 中零配置快速体验或制作演示,可通过 CDN 引入 Tailwind CSS。常见做法有两种:一是引入官方运行时 Play CDN 脚本(`<script src="https://cdn.tailwindcss.com"></script>`,v4 对应 `@tailwindcss/browser`),浏览器端按需解析类名;二是通过 jsDelivr 等静态 CDN 直接加载预编译样式表(如 `tailwindcss@3.3.0/dist/tailwind.min.css`)。CDN 方案优点是无需 Node 构建环境、开箱即用;缺点是静态预编译版无法自定义配置且体积庞大,运行时 Play CDN 则会在浏览器端承担编译开销,因此两者均适合演示与原型验证,不建议直接用于生产部署。

在基础 HTML 模板的 `<head>` 中加入视口元标签与 CDN 脚本后,即可直接为 `<h1>` 编写 `text-3xl font-bold underline` 输出带下划线的粗体标题。本站离线 Chromium 实测该标题计算结果:`fontSize` 为 `30px`、`lineHeight` 为 `36px`、`fontWeight` 为 `700`、`textDecorationLine` 为 `underline`。

Play CDN 扩展配置、自定义样式层与插件参数

使用官方 Play CDN 时,可在脚本加载后通过修改全局 `tailwind.config` 对象(例如在 `theme.extend.colors` 中注册 `clifford: '#da373d'`)扩展主题色,再直接在 HTML 中使用 `text-clifford`。本站离线 Chromium 核验该扩展色计算为 `rgb(218, 55, 61)`,同时完整保留 `30px` 字号与 `700` 字重。

如需补充自定义工具类并支持响应式前缀,可在 `<style type="text/tailwindcss">` 中利用 `@layer utilities` 定义 `.content-auto { content-visibility: auto; }`,再配合 `lg:content-auto` 按断点启用。本站离线 Chromium 跨视口实测:`800px` 宽度下 `contentVisibility` 维持 `visible`,切换至 `1024px` 后立即生效为 `auto`。

Play CDN 还支持在脚本 URL 中附加 `plugins` 查询参数(如 `?plugins=forms,typography,aspect-ratio,line-clamp,container-queries`)一键启用官方插件。本站离线脚本解析该参数得到全部 5 个插件标识,并在 Chromium 中核验排版插件 `.prose`(文字色 `rgb(55, 65, 81)`、行高 `28px`)与表单插件 `.form-input`(`1px` 边框、内边距 `8px 12px`)的渲染表现。

离线 Chromium 核验 CDN 基础排版、自定义色值、@layer 响应式工具类与插件样式

含完整源码 · 162 行
展开查看收起
python
"""Offline Playwright Chromium lab for Tailwind CSS Ch 03 (installbycdn)."""
import json
import os
from urllib.parse import parse_qs, urlparse
from playwright.sync_api import sync_playwright

BASE_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; }
  h1 { font-size: inherit; font-weight: inherit; margin: 0; }
}
@layer utilities {
  .text-3xl { font-size: 1.875rem; line-height: 2.25rem; }
  .font-bold { font-weight: 700; }
  .underline { text-decoration-line: underline; }
  .text-clifford { color: #da373d; }
  @media (min-width: 1024px) {
    .lg\\:content-auto { content-visibility: auto; }
  }
}
@layer components {
  .prose { color: #374151; max-width: 65ch; line-height: 1.75; }
  .prose h2 { color: #111827; font-weight: 700; font-size: 1.5rem; margin-top: 2rem; }
  .form-input { border: 1px solid #6b7280; padding: 0.5rem 0.75rem; line-height: 1.5rem; }
}
"""


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

        # Case 1: Basic Play CDN Hello world heading
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>{BASE_CSS}</style></head>
<body>
  <h1 id="hw" class="text-3xl font-bold underline">Hello world!</h1>
</body></html>""")
        actual1 = page.eval_on_selector("#hw", """el => {
            const s = getComputedStyle(el);
            return {
                text: el.textContent.trim(),
                fontSize: s.fontSize,
                lineHeight: s.lineHeight,
                fontWeight: s.fontWeight,
                textDecorationLine: s.textDecorationLine,
            };
        }""")
        expected1 = {
            "text": "Hello world!",
            "fontSize": "30px",
            "lineHeight": "36px",
            "fontWeight": "700",
            "textDecorationLine": "underline",
        }
        cases.append(dict(
            name="cdn_hello_world_heading",
            expected=expected1,
            actual=actual1,
            passed=(actual1 == expected1),
        ))

        # Case 2: Inline tailwind.config custom color clifford (#da373d)
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{BASE_CSS}</style></head>
<body>
  <h1 id="clifford" class="text-3xl font-bold underline text-clifford">Hello world!</h1>
</body></html>""")
        actual2 = page.eval_on_selector("#clifford", """el => {
            const s = getComputedStyle(el);
            return { color: s.color, fontSize: s.fontSize, fontWeight: s.fontWeight };
        }""")
        expected2 = {
            "color": "rgb(218, 55, 61)",
            "fontSize": "30px",
            "fontWeight": "700",
        }
        cases.append(dict(
            name="cdn_inline_tailwind_config_color",
            expected=expected2,
            actual=actual2,
            passed=(actual2 == expected2),
        ))

        # Case 3: Custom @layer utilities .content-auto with lg: breakpoint
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{BASE_CSS}</style></head>
<body>
  <div id="lazy" class="lg:content-auto">Long section</div>
</body></html>""")
        cv_800 = page.eval_on_selector("#lazy", "el => getComputedStyle(el).contentVisibility")
        page.set_viewport_size({"width": 1024, "height": 600})
        cv_1024 = page.eval_on_selector("#lazy", "el => getComputedStyle(el).contentVisibility")
        actual3 = {"at800px": cv_800, "at1024px": cv_1024}
        expected3 = {"at800px": "visible", "at1024px": "auto"}
        cases.append(dict(
            name="cdn_custom_layer_utilities_responsive",
            expected=expected3,
            actual=actual3,
            passed=(actual3 == expected3),
        ))

        # Case 4: Play CDN plugins query parsing + typography .prose / forms .form-input rendering
        cdn_url = "https://cdn.tailwindcss.com?plugins=forms,typography,aspect-ratio,line-clamp,container-queries"
        parsed_plugins = parse_qs(urlparse(cdn_url).query)["plugins"][0].split(",")
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{BASE_CSS}</style></head>
<body>
  <article id="doc" class="prose"><h2>Article</h2><p>Body</p></article>
  <input id="inp" class="form-input" type="text" />
</body></html>""")
        actual4 = page.evaluate("""(plugins) => {
            const ds = getComputedStyle(document.getElementById('doc'));
            const is = getComputedStyle(document.getElementById('inp'));
            return {
                plugins,
                proseColor: ds.color,
                proseLineHeight: ds.lineHeight,
                inputBorderWidth: is.borderTopWidth,
                inputPaddingTop: is.paddingTop,
                inputPaddingLeft: is.paddingLeft,
            };
        }""", parsed_plugins)
        expected4 = {
            "plugins": ["forms", "typography", "aspect-ratio", "line-clamp", "container-queries"],
            "proseColor": "rgb(55, 65, 81)",
            "proseLineHeight": "28px",
            "inputBorderWidth": "1px",
            "inputPaddingTop": "8px",
            "inputPaddingLeft": "12px",
        }
        cases.append(dict(
            name="cdn_plugins_prose_typography",
            expected=expected4,
            actual=actual4,
            passed=(actual4 == expected4),
        ))

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


if __name__ == "__main__":
    run()
核对 text-3xl/font-bold/underline(30px/36px/700/underline)、clifford 色 rgb(218,55,61)、lg:content-auto 在 800px/1024px 切换及 5 个 plugins 参数解析与 prose/form-input 样式。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

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

下载本章实验包 (mbskycom202612a648.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Tailwind CSS

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a648.zip

下载课程关联工程包:Tailwind CSS

课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a639.zip

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

Play CDN 在浏览器中运行即时编译器,支持 `tailwind.config`、`<style type="text/tailwindcss">` 和 `?plugins=...` 动态扩展;而静态预编译 CSS 文件固定打包了既定类集合,无法直接定制主题且体积较大。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习