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

离线验证 Bootstrap 4 默认排版基线、标题/语义元素及 18 项排版工具类

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-typography.py
explore-typography.py274 行
"""Offline Playwright Chromium lab for Bootstrap 4 Ch 04 (typography)."""
import json
from playwright.sync_api import sync_playwright

BS4_TYPO_CSS = """
*, *::before, *::after { box-sizing: border-box; }
html { font-size: 16px; }
body {
  margin: 0;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 1rem;
  font-weight: 400;
  line-height: 1.5;
  color: #212529;
  background-color: #fff;
}
p { margin-top: 0; margin-bottom: 1rem; }
h1, h2, h3, h4, h5, h6 { margin-top: 0; margin-bottom: 0.5rem; font-weight: 500; line-height: 1.2; }
h1 { font-size: 2.5rem; }
h2 { font-size: 2rem; }
h3 { font-size: 1.75rem; }
h4 { font-size: 1.5rem; }
h5 { font-size: 1.25rem; }
h6 { font-size: 1rem; }
.display-1 { font-size: 6rem; font-weight: 300; line-height: 1.2; }
.display-2 { font-size: 5.5rem; font-weight: 300; line-height: 1.2; }
.display-3 { font-size: 4.5rem; font-weight: 300; line-height: 1.2; }
.display-4 { font-size: 3.5rem; font-weight: 300; line-height: 1.2; }
small, .small { font-size: 80%; font-weight: 400; }
h1 small { color: #6c757d; }
mark, .mark { padding: 0.2em; background-color: #fcf8e3; }
abbr[title] { text-decoration: underline dotted; cursor: help; border-bottom: 0; }
.initialism { font-size: 90%; text-transform: uppercase; }
.blockquote { margin-bottom: 1rem; font-size: 1.25rem; }
.blockquote-footer { display: block; font-size: 80%; color: #6c757d; }
.blockquote-footer::before { content: "\\2014\\00A0"; }
dl { margin-top: 0; margin-bottom: 1rem; }
dt { font-weight: 700; }
dd { margin-bottom: 0.5rem; margin-left: 0; }
code { font-size: 87.5%; color: #e83e8c; font-family: SFMono-Regular, Menlo, Monaco, Consolas, monospace; }
kbd { padding: 0.2rem 0.4rem; font-size: 87.5%; color: #fff; background-color: #212529; border-radius: 0.2rem; font-family: monospace; }
pre { display: block; font-size: 87.5%; color: #212529; font-family: monospace; white-space: pre; }
.pre-scrollable { max-height: 340px; overflow-y: scroll; }
.font-weight-bold { font-weight: 700 !important; }
.font-weight-normal { font-weight: 400 !important; }
.font-weight-light { font-weight: 300 !important; }
.font-italic { font-style: italic !important; }
.lead { font-size: 1.25rem; font-weight: 300; }
.text-left { text-align: left !important; }
.text-center { text-align: center !important; }
.text-right { text-align: right !important; }
.text-justify { text-align: justify !important; }
.text-nowrap { white-space: nowrap !important; }
.text-lowercase { text-transform: lowercase !important; }
.text-uppercase { text-transform: uppercase !important; }
.text-capitalize { text-transform: capitalize !important; }
.list-unstyled { padding-left: 0; list-style: none; }
.list-inline { padding-left: 0; list-style: none; }
.list-inline-item { display: inline-block; margin-right: 0.5rem; }
"""

LONG_PRE = "\n".join(f"line {i:02d}: preserved   spaces" for i in range(1, 36))

HTML_PAGE = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{BS4_TYPO_CSS}</style></head>
<body>
  <p id="p-default">默认段落</p>
  <h1 id="h1">H1 <small id="h1-small">副标题</small></h1>
  <h2 id="h2">H2</h2><h3 id="h3">H3</h3><h4 id="h4">H4</h4><h5 id="h5">H5</h5><h6 id="h6">H6</h6>
  <h1 id="d1" class="display-1">D1</h1>
  <h1 id="d2" class="display-2">D2</h1>
  <h1 id="d3" class="display-3">D3</h1>
  <h1 id="d4" class="display-4">D4</h1>
  <p>演示 <mark id="mk">高亮</mark> 与 <abbr id="ab" title="World Health Organization">WHO</abbr> 及 <abbr id="ab-init" class="initialism" title="HyperText Markup Language">html</abbr></p>
  <blockquote id="bq" class="blockquote">
    <p>引用正文示例。</p>
    <footer id="bq-ft" class="blockquote-footer">来源说明</footer>
  </blockquote>
  <dl id="dl-box"><dt id="dt1">Coffee</dt><dd id="dd1">- black hot drink</dd></dl>
  <p><code id="cd">div</code> <kbd id="kb">ctrl + p</kbd></p>
  <pre id="pr">a   b\nc</pre>
  <pre id="pr-scroll" class="pre-scrollable">{LONG_PRE}</pre>

  <p id="u-bold" class="font-weight-bold">bold</p>
  <p id="u-norm" class="font-weight-normal">normal</p>
  <p id="u-light" class="font-weight-light">light</p>
  <p id="u-ital" class="font-italic">italic</p>
  <p id="u-lead" class="lead">lead</p>
  <p id="u-small" class="small">small</p>
  <p id="u-left" class="text-left">left</p>
  <p id="u-center" class="text-center">center</p>
  <p id="u-right" class="text-right">right</p>
  <p id="u-just" class="text-justify">justify</p>
  <p id="u-nowrap" class="text-nowrap">nowrap text</p>
  <p id="u-lower" class="text-lowercase">ABC</p>
  <p id="u-upper" class="text-uppercase">abc</p>
  <p id="u-cap" class="text-capitalize">hello world</p>
  <ul id="ul-unsty" class="list-unstyled">
    <li>A</li>
    <li>B<ul id="ul-nested"><li>Nested</li></ul></li>
  </ul>
  <ul id="ul-inline" class="list-inline">
    <li id="li-in1" class="list-inline-item">项1</li>
    <li id="li-in2" class="list-inline-item">项2</li>
    <li id="li-in3" class="list-inline-item">项3</li>
  </ul>
</body>
</html>
"""


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 1000, "height": 900})
        page.set_content(HTML_PAGE)

        # Case 1: body_defaults_and_headings
        res1 = page.evaluate("""() => {
            const bs = getComputedStyle(document.body);
            const ps = getComputedStyle(document.getElementById('p-default'));
            const hs = ['h1','h2','h3','h4','h5','h6'].map(id => parseFloat(getComputedStyle(document.getElementById(id)).fontSize));
            return {
                body_font_size: parseFloat(bs.fontSize),
                body_line_height: parseFloat(bs.lineHeight),
                p_margins: [parseFloat(ps.marginTop), parseFloat(ps.marginBottom)],
                heading_px: hs,
            };
        }""")
        expected_1 = {
            "body_font_size": 16.0,
            "body_line_height": 24.0,
            "p_margins": [0.0, 16.0],
            "heading_px": [40.0, 32.0, 28.0, 24.0, 20.0, 16.0],
        }
        cases.append(dict(name="body_defaults_and_headings", passed=(res1 == expected_1), expected=expected_1, actual=res1))

        # Case 2: display_headings_and_small
        res2 = page.evaluate("""() => {
            const ds = ['d1','d2','d3','d4'].map(id => {
                const s = getComputedStyle(document.getElementById(id));
                return { px: parseFloat(s.fontSize), weight: s.fontWeight };
            });
            const sm = getComputedStyle(document.getElementById('h1-small'));
            const usm = getComputedStyle(document.getElementById('u-small'));
            return {
                displays: ds,
                h1_small_px: parseFloat(sm.fontSize),
                h1_small_color: sm.color,
                utility_small_px: parseFloat(usm.fontSize),
            };
        }""")
        expected_2 = {
            "displays": [
                {"px": 96.0, "weight": "300"},
                {"px": 88.0, "weight": "300"},
                {"px": 72.0, "weight": "300"},
                {"px": 56.0, "weight": "300"},
            ],
            "h1_small_px": 32.0,
            "h1_small_color": "rgb(108, 117, 125)",
            "utility_small_px": 12.8,
        }
        cases.append(dict(name="display_headings_and_small", passed=(res2 == expected_2), expected=expected_2, actual=res2))

        # Case 3: semantic_mark_abbr_blockquote_dl
        res3 = page.evaluate("""() => {
            const mk = getComputedStyle(document.getElementById('mk'));
            const ab = getComputedStyle(document.getElementById('ab'));
            const bq = getComputedStyle(document.getElementById('bq'));
            const ft = getComputedStyle(document.getElementById('bq-ft'));
            const dt = getComputedStyle(document.getElementById('dt1'));
            const dd = getComputedStyle(document.getElementById('dd1'));
            return {
                mark_bg: mk.backgroundColor,
                abbr_cursor: ab.cursor,
                abbr_deco_style: ab.textDecorationStyle,
                blockquote_px: parseFloat(bq.fontSize),
                blockquote_footer_color: ft.color,
                dt_weight: dt.fontWeight,
                dd_margin_bottom: parseFloat(dd.marginBottom),
            };
        }""")
        expected_3 = {
            "mark_bg": "rgb(252, 248, 227)",
            "abbr_cursor": "help",
            "abbr_deco_style": "dotted",
            "blockquote_px": 20.0,
            "blockquote_footer_color": "rgb(108, 117, 125)",
            "dt_weight": "700",
            "dd_margin_bottom": 8.0,
        }
        cases.append(dict(name="semantic_mark_abbr_blockquote_dl", passed=(res3 == expected_3), expected=expected_3, actual=res3))

        # Case 4: code_kbd_pre_and_scrollable
        res4 = page.evaluate("""() => {
            const cd = getComputedStyle(document.getElementById('cd'));
            const kb = getComputedStyle(document.getElementById('kb'));
            const pr = getComputedStyle(document.getElementById('pr'));
            const scEl = document.getElementById('pr-scroll');
            const sc = getComputedStyle(scEl);
            return {
                code_color: cd.color,
                code_px: parseFloat(cd.fontSize),
                kbd_bg: kb.backgroundColor,
                kbd_color: kb.color,
                pre_whitespace: pr.whiteSpace,
                scrollable_max_h: sc.maxHeight,
                scrollable_overflow_y: sc.overflowY,
                scrollable_overflows: scEl.scrollHeight > scEl.clientHeight,
            };
        }""")
        expected_4 = {
            "code_color": "rgb(232, 62, 140)",
            "code_px": 14.0,
            "kbd_bg": "rgb(33, 37, 41)",
            "kbd_color": "rgb(255, 255, 255)",
            "pre_whitespace": "pre",
            "scrollable_max_h": "340px",
            "scrollable_overflow_y": "scroll",
            "scrollable_overflows": True,
        }
        cases.append(dict(name="code_kbd_pre_and_scrollable", passed=(res4 == expected_4), expected=expected_4, actual=res4))

        # Case 5: typography_utility_classes
        res5 = page.evaluate("""() => {
            const g = id => getComputedStyle(document.getElementById(id));
            const r1 = document.getElementById('li-in1').getBoundingClientRect();
            const r2 = document.getElementById('li-in2').getBoundingClientRect();
            const r3 = document.getElementById('li-in3').getBoundingClientRect();
            return {
                weights: [g('u-bold').fontWeight, g('u-norm').fontWeight, g('u-light').fontWeight],
                italic: g('u-ital').fontStyle,
                lead: [parseFloat(g('u-lead').fontSize), g('u-lead').fontWeight],
                aligns: [g('u-left').textAlign, g('u-center').textAlign, g('u-right').textAlign, g('u-just').textAlign],
                nowrap: g('u-nowrap').whiteSpace,
                transforms: [g('u-lower').textTransform, g('u-upper').textTransform, g('u-cap').textTransform],
                initialism: [parseFloat(g('ab-init').fontSize), g('ab-init').textTransform],
                list_unstyled: g('ul-unsty').listStyleType,
                list_nested_keeps_disc: g('ul-nested').listStyleType,
                list_inline_same_row: Math.round(r1.top) === Math.round(r2.top) && Math.round(r2.top) === Math.round(r3.top),
            };
        }""")
        expected_5 = {
            "weights": ["700", "400", "300"],
            "italic": "italic",
            "lead": [20.0, "300"],
            "aligns": ["left", "center", "right", "justify"],
            "nowrap": "nowrap",
            "transforms": ["lowercase", "uppercase", "capitalize"],
            "initialism": [14.4, "uppercase"],
            "list_unstyled": "none",
            "list_nested_keeps_disc": "circle",
            "list_inline_same_row": True,
        }
        cases.append(dict(name="typography_utility_classes", passed=(res5 == expected_5), expected=expected_5, actual=res5))

        browser.close()

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


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/bootstrap4-typography-lab/explore-typography.py

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

下载课程关联工程包:Bootstrap4

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

下载课程关联工程包:Bootstrap4

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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