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

Bootstrap4 多媒体对象

核对 Bootstrap 4 多媒体对象(.media 与 .media-body)在评论区与信息流中的基础排版、多层嵌套、头像右置及 align-self-* 垂直定位,并附离线 Chromium 实测尺寸数据。

学完这一章,你能够

  • 核对 Bootstrap 4 多媒体对象(.media 与 .media-body)在评论区与信息流中的基础排版、多层嵌套、头像右置及 align-self-* 垂直定位,并附离线 Chromium 实测尺寸数据。

基础多媒体对象结构与布局机理

Bootstrap 4 的多媒体对象(Media Object)专用于图文或音视频与说明文字并排呈现的界面模式,常见于博客评论列表、动态流与消息提醒。构建方式简洁直观:外层容器添加 `.media`(内部实现为 `display: flex; align-items: flex-start;`),多媒体元素(如头像图片)与文字内容块作为其直接子项,文字容器标注 `.media-body`(`flex: 1;` 自动占满剩余水平空间),再按需叠加 `.border`、`.p-3`、`.mr-3`、`.mt-3` 与 `.rounded-circle` 等工具类即可。本站离线 Chromium 在 `600px` 外框内实测 `60×60px` 圆形头像加 `.mr-3`(`16px`)与 `.border.p-3`:`.media` 计算为 `flex` + 顶部对齐,`.media-body` 的 `flex-grow` 为 `1`,文字区精确占据 `490px`(`600 - 2 - 32 - 60 - 16`)。

多媒体对象的层级嵌套

楼中楼评论与多级回复只需把新的 `.media` 子容器直接放入外层 `.media-body` 内部即可实现自然缩进嵌套,无需额外手写缩进边距。本站离线 Chromium 实测外层 `60px` 头像嵌套内层 `45px` 头像(内层带 `.p-3` 与 `.mr-3`):内层 `.media` 左边缘与外层 `.media-body` 完全对齐且排在外层正文段落下方,子级 `.media-body` 自动收缩适应剩余宽度 `397px`(`490 - 32 - 45 - 16`)。

头像右置与垂直对齐定位

若需要将头像或缩略图放在内容右侧,只需在 HTML 结构中将 `<img>` 移到 `.media-body` 之后,并将间距类由 `.mr-3` 改为 `.ml-3`。本站实测验证:调整顺序后 `60px` 头像自然落于正文右侧并与正文保持 `16px` 间距,`.media-body` 仍保持 `490px` 完整宽度。

由于 `.media` 本身是弹性容器,可直接通过 `.align-self-start`(顶部,默认)、`.align-self-center`(垂直居中)和 `.align-self-end`(底部)控制多媒体元素的纵向位置。本站在 `160px` 高的 `.media-body` 旁实测 `60×60px` 头像:三组类分别对应计算样式 `flex-start`、`center`、`flex-end`,头像相对 `.media` 顶部的实测偏移精确为 `0px`、`50px` 与 `100px`。

运行基础多媒体对象、楼中楼嵌套、头像右置与 align-self-* 垂直定位实测

含完整源码 · 226 行
展开查看收起
python
"""Offline Playwright Chromium verification for Bootstrap 4 Chapter 34: Media Objects."""
import json
import platform
from playwright.sync_api import sync_playwright

SVG_AVATAR = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='60' height='60'><rect width='60' height='60' fill='%23007bff'/></svg>"

BS4_MEDIA_CSS = """
* { box-sizing: border-box; }
html { font-size: 16px; }
body { margin: 0; padding: 0; font-family: Arial, sans-serif; }
.media { display: flex; align-items: flex-start; }
.media-body { flex: 1; }
.border { border: 1px solid #dee2e6 !important; }
.p-3 { padding: 1rem !important; }
.mr-3 { margin-right: 1rem !important; }
.ml-3 { margin-left: 1rem !important; }
.mt-3 { margin-top: 1rem !important; }
.rounded-circle { border-radius: 50% !important; }
.align-self-start { align-self: flex-start !important; }
.align-self-center { align-self: center !important; }
.align-self-end { align-self: flex-end !important; }
h4, p { margin: 0 0 8px 0; }
"""


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)
        try:
            page = browser.new_page(viewport={"width": 700, "height": 600})

            # Case 1: Basic media object (.media + .media-body)
            html1 = f"""<!doctype html><html><head><style>{BS4_MEDIA_CSS}</style></head><body>
  <div id="m1" class="media border p-3" style="width:600px">
    <img id="img1" src="{SVG_AVATAR}" alt="Avatar" class="mr-3 mt-3 rounded-circle" style="width:60px;height:60px;">
    <div id="body1" class="media-body">
      <h4>前端技术专栏</h4>
      <p>演示基础多媒体对象的弹性布局与文字自适应宽度。</p>
    </div>
  </div>
</body></html>"""
            page.set_content(html1)
            act1 = page.evaluate("""() => {
              const norm = v => v.replace(/^flow-/, 'flex-');
              const cm = getComputedStyle(document.getElementById('m1'));
              const cb = getComputedStyle(document.getElementById('body1'));
              const ci = getComputedStyle(document.getElementById('img1'));
              const ri = document.getElementById('img1').getBoundingClientRect();
              const rb = document.getElementById('body1').getBoundingClientRect();
              return {
                media_display: cm.display,
                media_align_items: norm(cm.alignItems),
                body_flex_grow: cb.flexGrow,
                img_width: Math.round(ri.width),
                img_radius: ci.borderRadius,
                gap_px: Math.round(rb.left - ri.right),
                body_width: Math.round(rb.width)
              };
            }""")
            exp1 = {
                "media_display": "flex",
                "media_align_items": "flex-start",
                "body_flex_grow": "1",
                "img_width": 60,
                "img_radius": "50%",
                "gap_px": 16,
                "body_width": 490,
            }
            cases.append(dict(
                name="basic_media_object",
                inputs=dict(container_width=600, avatar_width=60, padding_px=16, margin_right_px=16),
                prerequisites="600px 容器加 .media.border.p-3,左侧 60x60 圆形头像加 .mr-3.mt-3.rounded-circle",
                action="验证 .media 弹性对齐、.media-body 的 flex: 1 扩展及计算后正文宽度 490px。",
                expected=exp1,
                actual=act1,
                measurements=dict(formula="600 - 2(border) - 32(p-3) - 60(img) - 16(mr-3) = 490"),
                passed=(act1 == exp1),
            ))

            # Case 2: Nested media object
            html2 = f"""<!doctype html><html><head><style>{BS4_MEDIA_CSS}</style></head><body>
  <div id="outer" class="media border p-3" style="width:600px">
    <img id="oimg" src="{SVG_AVATAR}" alt="User A" class="mr-3 mt-3 rounded-circle" style="width:60px;height:60px;">
    <div id="obody" class="media-body">
      <h4>主评论</h4>
      <p id="opara">主评论正文内容。</p>
      <div id="inner" class="media p-3">
        <img id="iimg" src="{SVG_AVATAR}" alt="User B" class="mr-3 mt-3 rounded-circle" style="width:45px;height:45px;">
        <div id="ibody" class="media-body">
          <h4>嵌套回复</h4>
          <p>放在外层 .media-body 内部的子级多媒体对象。</p>
        </div>
      </div>
    </div>
  </div>
</body></html>"""
            page.set_content(html2)
            act2 = page.evaluate("""() => {
              const ro = document.getElementById('obody').getBoundingClientRect();
              const rp = document.getElementById('opara').getBoundingClientRect();
              const ri = document.getElementById('inner').getBoundingClientRect();
              const iimg = document.getElementById('iimg').getBoundingClientRect();
              const ib = document.getElementById('ibody').getBoundingClientRect();
              return {
                inner_aligned_with_outer_body: Math.round(ri.left) === Math.round(ro.left),
                inner_below_outer_para: ri.top >= rp.bottom,
                inner_img_width: Math.round(iimg.width),
                inner_body_width: Math.round(ib.width)
              };
            }""")
            # inner width = 490, padding 32, iimg 45, mr-3 16 => ibody = 490 - 32 - 45 - 16 = 397
            exp2 = {
                "inner_aligned_with_outer_body": True,
                "inner_below_outer_para": True,
                "inner_img_width": 45,
                "inner_body_width": 397,
            }
            cases.append(dict(
                name="nested_media_object",
                inputs=dict(outer_avatar=60, inner_avatar=45),
                prerequisites="内层 .media.p-3 嵌套在外层 .media-body 中,子级头像宽 45px",
                action="测量嵌套多媒体对象与外层正文的左对齐缩进关系及子级正文自适应宽度 397px。",
                expected=exp2,
                actual=act2,
                measurements=dict(formula="490 - 32(p-3) - 45(img) - 16(mr-3) = 397"),
                passed=(act2 == exp2),
            ))

            # Case 3: Right-aligned media image (image placed after .media-body)
            html3 = f"""<!doctype html><html><head><style>{BS4_MEDIA_CSS}</style></head><body>
  <div id="mr" class="media border p-3" style="width:600px">
    <div id="rbody" class="media-body">
      <h4>右置头像布局</h4>
      <p>将图像元素放在 .media-body 之后并配合 .ml-3 实现右置展示。</p>
    </div>
    <img id="rimg" src="{SVG_AVATAR}" alt="User Right" class="ml-3 mt-3 rounded-circle" style="width:60px;height:60px;">
  </div>
</body></html>"""
            page.set_content(html3)
            act3 = page.evaluate("""() => {
              const rb = document.getElementById('rbody').getBoundingClientRect();
              const ri = document.getElementById('rimg').getBoundingClientRect();
              return {
                img_right_of_body: ri.left > rb.right,
                gap_px: Math.round(ri.left - rb.right),
                body_width: Math.round(rb.width),
                img_width: Math.round(ri.width)
              };
            }""")
            exp3 = {"img_right_of_body": True, "gap_px": 16, "body_width": 490, "img_width": 60}
            cases.append(dict(
                name="media_image_right",
                inputs=dict(dom_order=["media-body", "img.ml-3"]),
                prerequisites="DOM 中 .media-body 在前、60px 头像在后并添加 .ml-3",
                action="核对头像位于正文右侧且间距为 16px、正文仍占据 490px。",
                expected=exp3,
                actual=act3,
                measurements=dict(margin_left_px=16),
                passed=(act3 == exp3),
            ))

            # Case 4: Vertical alignment with align-self-start / center / end
            html4 = f"""<!doctype html><html><head><style>{BS4_MEDIA_CSS}</style></head><body>
  <div id="ms" class="media" style="width:500px">
    <img id="is" src="{SVG_AVATAR}" class="align-self-start mr-3" style="width:60px;height:60px;">
    <div class="media-body" style="height:160px"><h4>头部对齐</h4></div>
  </div>
  <div id="mc" class="media" style="width:500px">
    <img id="ic" src="{SVG_AVATAR}" class="align-self-center mr-3" style="width:60px;height:60px;">
    <div class="media-body" style="height:160px"><h4>居中对齐</h4></div>
  </div>
  <div id="me" class="media" style="width:500px">
    <img id="ie" src="{SVG_AVATAR}" class="align-self-end mr-3" style="width:60px;height:60px;">
    <div class="media-body" style="height:160px"><h4>底部对齐</h4></div>
  </div>
</body></html>"""
            page.set_content(html4)
            act4 = page.evaluate("""() => {
              const norm = v => v.replace(/^flow-/, 'flex-');
              const info = (mid, iid) => {
                const mr = document.getElementById(mid).getBoundingClientRect();
                const ir = document.getElementById(iid).getBoundingClientRect();
                return {
                  alignSelf: norm(getComputedStyle(document.getElementById(iid)).alignSelf),
                  relTop: Math.round(ir.top - mr.top)
                };
              };
              return {
                start: info('ms', 'is'),
                center: info('mc', 'ic'),
                end: info('me', 'ie')
              };
            }""")
            exp4 = {
                "start": {"alignSelf": "flex-start", "relTop": 0},
                "center": {"alignSelf": "center", "relTop": 50},
                "end": {"alignSelf": "flex-end", "relTop": 100},
            }
            cases.append(dict(
                name="media_vertical_alignment",
                inputs=dict(body_height=160, img_height=60, classes=["align-self-start", "align-self-center", "align-self-end"]),
                prerequisites="三组 .media 正文区固定 160px 高,60px 头像分别应用 align-self-start/center/end",
                action="读取头像计算 alignSelf 及相对 .media 顶部的偏移像素(0px、50px、100px)。",
                expected=exp4,
                actual=act4,
                measurements=dict(vertical_slack_px=100),
                passed=(act4 == exp4),
            ))
        finally:
            browser.close()

    print(json.dumps(dict(version=platform.python_version(), system=platform.system(), cases=cases), ensure_ascii=False))


if __name__ == "__main__":
    main()
核对 600px 外框下基础 .media-body 宽 490px 与 16px 间距、嵌套子级左对齐缩进且正文宽 397px、右置头像位于正文右侧间距 16px,以及 160px 正文旁 60px 头像在 start/center/end 下的相对顶距 0px/50px/100px。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:Bootstrap4

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

下载课程关联工程包:Bootstrap4

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

放进外层 `.media-body` 后,子级 `.media` 处于外层头像右侧的主内容列中,因此自动继承与父级正文一致的左缩进边界;若与外层 `.media` 并列,则会顶格从最左侧开始排列,失去层级嵌套的视觉从属关系。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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