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

Bootstrap5 卡片

核对 Bootstrap 5 卡片弹性容器结构、页眉页脚、标题正文链接、9 种背景色、上下图文与覆盖层,以及 BS5 卡片网格迁移。

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

学完这一章,你能够

卡片组件定位与核心样式类

卡片(Card)是 Bootstrap 5 中极具扩展性的内容容器,广泛用于博客摘要、资料卡与仪表盘模块。其核心由外层 `.card`、内容区 `.card-body`、标题 `.card-title`、副标题 `.card-subtitle`、正文 `.card-text`、页眉 `.card-header`、页脚 `.card-footer` 以及顶部/底部图片类 `.card-img-top`/`.card-img-bottom` 组成;多卡片网格布局在 Bootstrap 5 中以网格 `.row`/`.col` 取代了已移除的 `.card-deck` 与 `.card-columns`,而无缝拼接的 `.card-group` 依然保留。

简单卡片、头部底部与正文链接

最简卡片仅需在 `.card` 内放置 `.card-body`。本站离线 Chromium 实测 `.card` 采用 `display: flex; flex-direction: column`、`6px` 圆角,`.card-body` 默认四周内边距 `16px`。

添加 `.card-header` 与 `.card-footer` 可在正文上下划分浅灰底分隔区,常用于放置分类标题、元信息或操作按钮。实测三者自上而下依次衔接且由 `1px` 细线清晰分隔。

在 `.card-body` 中使用 `.card-title`、`.card-subtitle`、`.card-text` 与 `.card-link` 可规范文字间距:最后一个 `.card-text` 会自动清除底边距(实测首段 `margin-bottom: 16px`、末段 `0px`),相邻 `.card-link` 之间自动添加 `16px` 左外边距。

语义背景色、图片卡片与覆盖层

为 `.card` 叠加 `.bg-primary`、`.bg-success`、`.bg-info`、`.bg-warning`、`.bg-danger`、`.bg-secondary`、`.bg-dark`(配合 `.text-white`)及 `.bg-light`(配合 `.text-dark`)可快速定制主题色卡片。实测 9 种基础与语义色卡片的背景与文字颜色均与 Bootstrap 5 规范一致。

将 `<img>` 置于 `.card-body` 之前并加 `.card-img-top`,或置于 `.card-body` 之后并加 `.card-img-bottom`,可自动贴合卡片顶部或底部的内圆角(实测顶部图片上圆角 `5px`、下圆角 `0px`,且严格位于正文上方/下方)。

若需将图片作为卡片背景并在其上方直接叠加标题与按钮,将 `.card-body` 替换为 `.card-img-overlay` 即可。实测 `.card-img-overlay` 计算定位为 `position: absolute`,左上坐标与底层图片完全重合。此外,实测 BS5 网格 `.row > .col > .card.h-100` 生成 3 张 `200px` 等宽等高且间距 `16px` 的卡片,而 `.card-group` 则通过 `-1px` 边距和内侧零圆角实现紧贴拼接。

Bootstrap 5 卡片核心样式类与迁移核对表

类名作用与 Bootstrap 5 状态说明典型用法
.card卡片最外层弹性列容器,提供边框与圆角。<div class="card">...</div>
.card-body卡片主内容区,默认提供 1rem(16px)内边距。<div class="card-body">...</div>
.card-title卡片主标题样式,置于 .card-body 或覆盖层内。<h5 class="card-title">Card Title</h5>
.card-text卡片正文段落,末项自动清除底部外边距。<p class="card-text">Some quick example text...</p>
.card-img-top卡片顶部配图,自动贴合卡片顶部内圆角。<img src="image.jpg" class="card-img-top">
.card-img-bottom卡片底部配图,自动贴合卡片底部内圆角。<img src="image.jpg" class="card-img-bottom">
.card-header卡片页眉区域,带浅灰底与底部分隔线。<div class="card-header">Card Header</div>
.card-footer卡片页脚区域,带浅灰底与顶部分隔线。<div class="card-footer">Card Footer</div>
.card-link卡片行内链接,相邻链接自动增加 1rem 左间距。<a href="#" class="card-link">Card link</a>
.card-deckBootstrap 5 已移除,改用 .row / .col 与 .h-100 实现带间隙等高卡片。<div class="row row-cols-3 g-3">...</div>
.card-groupBootstrap 5 仍保留:将多张卡片无缝紧贴拼接为等宽等高组(如需间隙请用网格 .row/.col)。<div class="card-group">...</div>
.card-columnsBootstrap 5 已移除瀑布流多列类,官方建议改用网格 .row/.col 或集成 Masonry。<div class="row" data-masonry="...">...</div>
.card-subtitle卡片副标题,紧跟 .card-title 下方显示。<h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6>
.card-img-overlay绝对定位覆盖层,将文本与按钮直接叠加在卡片图片之上。<div class="card-img-overlay">Overlay content</div>

在离线 Chromium 中验证卡片三段结构、9 色卡片、图片覆盖层及 BS5 网格/卡片组对比

python · 阅读源码
"""Offline Playwright Chromium verification for Bootstrap 5 Cards (Ch 18)."""
import json
from playwright.sync_api import sync_playwright

SVG_DATA = (
    "data:image/svg+xml;utf8,"
    "<svg xmlns='http://www.w3.org/2000/svg' width='400' height='200'>"
    "<rect width='400' height='200' fill='%236c757d'/>"
    "<text x='200' y='105' fill='white' font-size='20' text-anchor='middle'>Card Image</text>"
    "</svg>"
)

HTML = f"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<style>
  *, *::before, *::after {{ box-sizing: border-box; }}
  html {{ font-size: 16px; }}
  body {{ margin: 16px; font-family: system-ui, -apple-system, "Segoe UI", sans-serif; line-height: 1.5; }}
  .card {{
    position: relative; display: flex; flex-direction: column; min-width: 0;
    word-wrap: break-word; background-color: #fff; background-clip: border-box;
    border: 1px solid rgba(0, 0, 0, 0.175); border-radius: 0.375rem; margin-bottom: 12px;
  }}
  .card-body {{ flex: 1 1 auto; padding: 1rem 1rem; }}
  .card-title {{ margin: 0 0 0.5rem 0; font-size: 1.25rem; }}
  .card-subtitle {{ margin-top: -0.25rem; margin-bottom: 0.5rem; color: #6c757d; }}
  .card-text {{ margin-top: 0; margin-bottom: 1rem; }}
  .card-text:last-child {{ margin-bottom: 0; }}
  .card-link {{ color: #0d6efd; text-decoration: underline; }}
  .card-link + .card-link {{ margin-left: 1rem; }}
  .card-header {{
    padding: 0.5rem 1rem; margin-bottom: 0; background-color: rgba(0, 0, 0, 0.03);
    border-bottom: 1px solid rgba(0, 0, 0, 0.175);
  }}
  .card-footer {{
    padding: 0.5rem 1rem; background-color: rgba(0, 0, 0, 0.03);
    border-top: 1px solid rgba(0, 0, 0, 0.175);
  }}
  .card-img-top {{ width: 100%; display: block; border-top-left-radius: calc(0.375rem - 1px); border-top-right-radius: calc(0.375rem - 1px); }}
  .card-img-bottom {{ width: 100%; display: block; border-bottom-right-radius: calc(0.375rem - 1px); border-bottom-left-radius: calc(0.375rem - 1px); }}
  .card-img-overlay {{ position: absolute; top: 0; right: 0; bottom: 0; left: 0; padding: 1rem; }}
  .bg-primary {{ background-color: #0d6efd !important; }}
  .bg-success {{ background-color: #198754 !important; }}
  .bg-info {{ background-color: #0dcaf0 !important; }}
  .bg-warning {{ background-color: #ffc107 !important; }}
  .bg-danger {{ background-color: #dc3545 !important; }}
  .bg-secondary {{ background-color: #6c757d !important; }}
  .bg-dark {{ background-color: #212529 !important; }}
  .bg-light {{ background-color: #f8f9fa !important; }}
  .text-white {{ color: #fff !important; }}
  .text-dark {{ color: #212529 !important; }}
  .row {{ display: flex; flex-wrap: wrap; width: 632px; gap: 16px; }}
  .col {{ flex: 1 0 0%; }}
  .h-100 {{ height: 100%; margin-bottom: 0; }}
  .card-group {{ display: flex; flex-flow: row wrap; width: 600px; }}
  .card-group > .card {{ flex: 1 0 0%; margin-bottom: 0; }}
  .card-group > .card + .card {{ margin-left: -1px; border-top-left-radius: 0; border-bottom-left-radius: 0; }}
  .card-group > .card:not(:last-child) {{ border-top-right-radius: 0; border-bottom-right-radius: 0; }}
</style>
</head>
<body>
<div id="c-full" class="card" style="width:360px">
  <div id="c-hdr" class="card-header">头部</div>
  <div id="c-body" class="card-body">
    <h5 id="c-title" class="card-title">Card Title</h5>
    <h6 id="c-sub" class="card-subtitle">Card subtitle</h6>
    <p id="c-p1" class="card-text">First paragraph.</p>
    <p id="c-p2" class="card-text">Last paragraph.</p>
  </div>
  <div id="c-ftr" class="card-footer">底部</div>
</div>

<div id="c-links" class="card" style="width:360px">
  <div class="card-body">
    <a id="lk-1" href="#" class="card-link">Card link</a>
    <a id="lk-2" href="#" class="card-link">Another link</a>
  </div>
</div>

<section id="sec-colors" style="width:360px">
  <div id="cc-base" class="card"><div class="card-body">基础</div></div>
  <div id="cc-primary" class="card bg-primary text-white"><div class="card-body">主要</div></div>
  <div id="cc-success" class="card bg-success text-white"><div class="card-body">成功</div></div>
  <div id="cc-info" class="card bg-info text-white"><div class="card-body">信息</div></div>
  <div id="cc-warning" class="card bg-warning text-white"><div class="card-body">警告</div></div>
  <div id="cc-danger" class="card bg-danger text-white"><div class="card-body">危险</div></div>
  <div id="cc-secondary" class="card bg-secondary text-white"><div class="card-body">次要</div></div>
  <div id="cc-dark" class="card bg-dark text-white"><div class="card-body">黑色</div></div>
  <div id="cc-light" class="card bg-light text-dark"><div class="card-body">浅色</div></div>
</section>

<div id="c-img-top" class="card" style="width:400px">
  <img id="img-top" class="card-img-top" src="{SVG_DATA}" alt="Card image">
  <div id="img-top-body" class="card-body"><h4 class="card-title">John Doe</h4><p class="card-text">Some example text.</p></div>
</div>

<div id="c-img-bottom" class="card" style="width:400px">
  <div id="img-bot-body" class="card-body"><h4 class="card-title">Bottom Image</h4></div>
  <img id="img-bot" class="card-img-bottom" src="{SVG_DATA}" alt="Card image">
</div>

<div id="c-overlay" class="card" style="width:400px">
  <img id="img-ov" class="card-img-top" src="{SVG_DATA}" alt="Card image">
  <div id="ov-layer" class="card-img-overlay text-white"><h4 class="card-title">Overlay Title</h4></div>
</div>

<div id="bs5-grid" class="row">
  <div class="col"><div id="g-c1" class="card h-100"><div class="card-body">短文</div></div></div>
  <div class="col"><div id="g-c2" class="card h-100"><div class="card-body">多行较长说明文字用于检验等高卡片对齐效果</div></div></div>
  <div class="col"><div id="g-c3" class="card h-100"><div class="card-body">短文</div></div></div>
</div>

<div id="bs5-group" class="card-group" style="margin-top:16px">
  <div id="cg-1" class="card"><div class="card-body">组卡片 1</div></div>
  <div id="cg-2" class="card"><div class="card-body">组卡片 2</div></div>
</div>
</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():
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 1000, "height": 1200})
        page.set_content(HTML, wait_until="load")

        c1_actual = page.evaluate("""() => {
            const c = getComputedStyle(document.getElementById("c-full"));
            const b = getComputedStyle(document.getElementById("c-body"));
            const p1 = getComputedStyle(document.getElementById("c-p1"));
            const p2 = getComputedStyle(document.getElementById("c-p2"));
            const lk2 = getComputedStyle(document.getElementById("lk-2"));
            const hdr = document.getElementById("c-hdr").getBoundingClientRect();
            const body = document.getElementById("c-body").getBoundingClientRect();
            const ftr = document.getElementById("c-ftr").getBoundingClientRect();
            return {
                card_display: c.display,
                card_flex_dir: c.flexDirection,
                card_radius: c.borderTopLeftRadius,
                body_padding: b.padding,
                first_text_mb: p1.marginBottom,
                last_text_mb: p2.marginBottom,
                second_link_ml: lk2.marginLeft,
                header_body_footer_order: hdr.bottom <= body.top + 1 && body.bottom <= ftr.top + 1,
            };
        }""")
        c1_expected = {
            "card_display": "flex",
            "card_flex_dir": "column",
            "card_radius": "6px",
            "body_padding": "16px",
            "first_text_mb": "16px",
            "last_text_mb": "0px",
            "second_link_ml": "16px",
            "header_body_footer_order": True,
        }

        c2_actual = page.evaluate("""() => {
            const bg = id => getComputedStyle(document.getElementById(id)).backgroundColor;
            return {
                base: bg("cc-base"),
                primary: bg("cc-primary"),
                success: bg("cc-success"),
                info: bg("cc-info"),
                warning: bg("cc-warning"),
                danger: bg("cc-danger"),
                secondary: bg("cc-secondary"),
                dark: bg("cc-dark"),
                light: bg("cc-light"),
                light_text: getComputedStyle(document.getElementById("cc-light")).color,
                primary_text: getComputedStyle(document.getElementById("cc-primary")).color,
            };
        }""")
        c2_expected = {
            "base": "rgb(255, 255, 255)",
            "primary": "rgb(13, 110, 253)",
            "success": "rgb(25, 135, 84)",
            "info": "rgb(13, 202, 240)",
            "warning": "rgb(255, 193, 7)",
            "danger": "rgb(220, 53, 69)",
            "secondary": "rgb(108, 117, 125)",
            "dark": "rgb(33, 37, 41)",
            "light": "rgb(248, 249, 250)",
            "light_text": "rgb(33, 37, 41)",
            "primary_text": "rgb(255, 255, 255)",
        }

        c3_actual = page.evaluate("""() => {
            const it = document.getElementById("img-top").getBoundingClientRect();
            const itb = document.getElementById("img-top-body").getBoundingClientRect();
            const ib = document.getElementById("img-bot").getBoundingClientRect();
            const ibb = document.getElementById("img-bot-body").getBoundingClientRect();
            const ovImg = document.getElementById("img-ov").getBoundingClientRect();
            const ov = document.getElementById("ov-layer").getBoundingClientRect();
            const ovStyle = getComputedStyle(document.getElementById("ov-layer"));
            const topStyle = getComputedStyle(document.getElementById("img-top"));
            return {
                img_top_above_body: it.bottom <= itb.top + 1,
                img_top_radius: [topStyle.borderTopLeftRadius, topStyle.borderBottomLeftRadius],
                img_bottom_below_body: ib.top >= ibb.bottom - 1,
                overlay_position: ovStyle.position,
                overlay_covers_image: Math.round(ov.top) === Math.round(ovImg.top) && Math.round(ov.left) === Math.round(ovImg.left),
            };
        }""")
        c3_expected = {
            "img_top_above_body": True,
            "img_top_radius": ["5px", "0px"],
            "img_bottom_below_body": True,
            "overlay_position": "absolute",
            "overlay_covers_image": True,
        }

        c4_actual = page.evaluate("""() => {
            const r1 = document.getElementById("g-c1").getBoundingClientRect();
            const r2 = document.getElementById("g-c2").getBoundingClientRect();
            const r3 = document.getElementById("g-c3").getBoundingClientRect();
            const cg1 = getComputedStyle(document.getElementById("cg-1"));
            const cg2 = getComputedStyle(document.getElementById("cg-2"));
            return {
                grid_equal_width: Math.round(r1.width) === 200 && Math.round(r2.width) === 200 && Math.round(r3.width) === 200,
                grid_equal_height: Math.round(r1.height) === Math.round(r2.height) && Math.round(r2.height) === Math.round(r3.height),
                grid_gap_px: Math.round(r2.left - r1.right),
                card_group_inner_radius_collapsed: cg1.borderTopRightRadius === "0px" && cg2.borderTopLeftRadius === "0px",
                card_group_margin_left: cg2.marginLeft,
            };
        }""")
        c4_expected = {
            "grid_equal_width": True,
            "grid_equal_height": True,
            "grid_gap_px": 16,
            "card_group_inner_radius_collapsed": True,
            "card_group_margin_left": "-1px",
        }

        browser.close()

    cases = [
        dict(name="card_structure_header_footer", description="核对 .card 弹性列结构、页眉/正文/页脚顺序、末段 .card-text 零底边距及 .card-link 间距", expected=c1_expected, actual=c1_actual, passed=c1_actual == c1_expected),
        dict(name="contextual_colored_cards", description="核对 9 种基础与语义背景色卡片(含 text-white/text-dark)", expected=c2_expected, actual=c2_actual, passed=c2_actual == c2_expected),
        dict(name="card_image_top_bottom_overlay", description="核对 .card-img-top/.card-img-bottom 上下排版圆角与 .card-img-overlay 绝对定位覆盖", expected=c3_expected, actual=c3_actual, passed=c3_actual == c3_expected),
        dict(name="bs5_card_layout_grid_vs_group", description="核对 BS5 网格 row/col + h-100 等高等宽卡片与保留的 .card-group 无缝拼接", expected=c4_expected, actual=c4_actual, passed=c4_actual == c4_expected),
    ]
    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 flex 列布局与末段零底边距、9 种语义色、顶部/底部/覆盖层图片坐标,以及 .row/.col 等高间距与 .card-group 无缝拼接。
在离线 Chromium 中验证卡片三段结构、9 色卡片、图片覆盖层及 BS5 网格/卡片组对比

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

当前源码 SHA256:09f55c33d0af3f845bd5a1d3124b01273760610c7b2245be33757ba6d93b2f72

下载本站示例源码

本地运行

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

下载Bootstrap5 卡片实验

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

ZIP SHA256:a0897f9762fde5599f3ad276e245ead299796d08c6bd525d33ed9f8021e5920a

常见错误与边界

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

练习与解答

Bootstrap 5 中 `.card-deck`、`.card-columns` 和 `.card-group` 的支持状态分别是什么?

展开参考解答

Bootstrap 5 移除了 `.card-deck` 和 `.card-columns`(统一改由响应式网格 `.row`/`.col` + `.h-100` 或 Masonry 实现),而 `.card-group` 仍保留用于将卡片无缝紧贴拼接。

规范与官方依据