蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-basic.py
explore-basic.py272 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/tailwindcss-basic-lab/explore-basic.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-basic.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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