Bootstrap4 图像形状
核对 Bootstrap 4 圆角、椭圆、缩略图三类图像外观,左右浮动与块级居中对齐生效前提,以及 .img-fluid 响应式按比例缩放实测。
学完这一章,你能够
- 核对 Bootstrap 4 圆角、椭圆、缩略图三类图像外观,左右浮动与块级居中对齐生效前提,以及 .img-fluid 响应式按比例缩放实测。
圆角、椭圆与缩略图形状类
Bootstrap 4 通过 3 个常用类快速塑造 `<img>` 外观:`.rounded` 添加 `0.25rem`(实测 `4px`)圆角;`.rounded-circle` 设置 `border-radius: 50%`(方形图片呈正圆,长方形图片呈椭圆);`.img-thumbnail` 构造带相框感的缩略图,本站实测其具备 `4px` 白色内边距(`background-color: rgb(255, 255, 255)`)、`1px solid rgb(222, 226, 230)` 外边框与 `4px` 圆角。
浮动对齐与块级水平居中
使用 `.float-left` 与 `.float-right` 可让图片贴靠容器左右两侧;为避免后续文档流高度塌陷,父容器通常配合 `.clearfix` 清除浮动。本站在 `800px` 容器中实测:`.float-left` 图像紧贴左边缘 `x = 0px`,`.float-right` 图像右缘贴合 `800px`,两者处于同一水平行。
让单张图片水平居中必须同时添加 `.mx-auto`(左右外边距 `auto`)与 `.d-block`(`display: block`)。本站对比实测证明:`<img>` 默认属于行内替换元素,若仅加 `.mx-auto` 不加 `.d-block`,其 `display` 仍为 `inline` 并停留在最左侧 `x = 0px`;叠加 `.d-block` 后,`200px` 宽图像在 `800px` 容器中精确居中,左右留白均为 `300px`。
响应式图片 .img-fluid
不同屏幕尺寸下需防止大图撑出容器或失真变形。给 `<img>` 添加 `.img-fluid` 即应用 `max-width: 100%; height: auto;`:当容器窄于图片原始宽度时等比缩小,当容器宽于图片原始宽度时维持原尺寸不强行拉伸。本站用 `800×400` 本地内联 SVG 实测:在 `375px` 视口(内容区 `345px`)下等比缩放至 `345×173px`,而在 `1200px` 宽视口下保持固有尺寸 `800×400px`。
离线验证 Bootstrap 4 图像形状、浮动对齐、块级居中与 .img-fluid 等比缩放
展开查看收起
"""Offline Playwright Chromium lab for Bootstrap 4 Ch 07 (images)."""
import json
from urllib.parse import quote
from playwright.sync_api import sync_playwright
def svg_data_uri(w: int, h: int, color: str) -> str:
svg = f'<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="{h}"><rect width="{w}" height="{h}" fill="{color}"/></svg>'
return "data:image/svg+xml;utf8," + quote(svg)
IMG_200 = svg_data_uri(200, 150, "#4a90d9")
IMG_800 = svg_data_uri(800, 400, "#2e7d32")
BS4_IMG_CSS = """
*, *::before, *::after { box-sizing: border-box; }
body { margin: 0; font-family: sans-serif; }
.rounded { border-radius: 0.25rem !important; }
.rounded-circle { border-radius: 50% !important; }
.img-thumbnail { padding: 0.25rem; background-color: #fff; border: 1px solid #dee2e6; border-radius: 0.25rem; max-width: 100%; height: auto; }
.float-left { float: left !important; }
.float-right { float: right !important; }
.clearfix::after { display: block; clear: both; content: ""; }
.mx-auto { margin-right: auto !important; margin-left: auto !important; }
.d-block { display: block !important; }
.img-fluid { max-width: 100%; height: auto; }
.stage { width: 800px; margin: 0; }
.fluid-wrap { width: 100%; padding: 0 15px; }
"""
HTML_PAGE = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{BS4_IMG_CSS}</style></head>
<body>
<div class="stage">
<img id="img-rounded" src="{IMG_200}" class="rounded" alt="rounded">
<img id="img-circle" src="{IMG_200}" class="rounded-circle" alt="circle">
<img id="img-thumb" src="{IMG_200}" class="img-thumbnail" alt="thumb">
</div>
<div id="float-stage" class="stage clearfix">
<img id="img-fl" src="{IMG_200}" class="float-left" alt="left">
<img id="img-fr" src="{IMG_200}" class="float-right" alt="right">
</div>
<div id="center-stage" class="stage">
<img id="img-mx-only" src="{IMG_200}" class="mx-auto" alt="inline">
<img id="img-mx-block" src="{IMG_200}" class="mx-auto d-block" alt="centered">
</div>
<div id="fluid-stage" class="fluid-wrap">
<img id="img-fluid" src="{IMG_800}" class="img-fluid" alt="fluid">
</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():
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: image_shape_classes
res1 = page.evaluate("""() => {
const sr = getComputedStyle(document.getElementById('img-rounded'));
const sc = getComputedStyle(document.getElementById('img-circle'));
const st = getComputedStyle(document.getElementById('img-thumb'));
return {
rounded_radius: sr.borderRadius,
circle_radius: sc.borderRadius,
thumb_padding: st.paddingTop,
thumb_border: st.borderTopWidth + ' ' + st.borderTopStyle + ' ' + st.borderTopColor,
thumb_radius: st.borderRadius,
thumb_bg: st.backgroundColor,
};
}""")
expected_1 = {
"rounded_radius": "4px",
"circle_radius": "50%",
"thumb_padding": "4px",
"thumb_border": "1px solid rgb(222, 226, 230)",
"thumb_radius": "4px",
"thumb_bg": "rgb(255, 255, 255)",
}
cases.append(dict(name="image_shape_classes", passed=(res1 == expected_1), expected=expected_1, actual=res1))
# Case 2: float_left_and_right_alignment
res2 = page.evaluate("""() => {
const box = document.getElementById('float-stage').getBoundingClientRect();
const l = document.getElementById('img-fl');
const r = document.getElementById('img-fr');
const lr = l.getBoundingClientRect();
const rr = r.getBoundingClientRect();
return {
left_float: getComputedStyle(l).float,
right_float: getComputedStyle(r).float,
left_x: Math.round(lr.left - box.left),
right_edge: Math.round(rr.right - box.left),
same_row: Math.round(lr.top) === Math.round(rr.top),
};
}""")
expected_2 = {
"left_float": "left",
"right_float": "right",
"left_x": 0,
"right_edge": 800,
"same_row": True,
}
cases.append(dict(name="float_left_and_right_alignment", passed=(res2 == expected_2), expected=expected_2, actual=res2))
# Case 3: center_image_mx_auto_d_block
res3 = page.evaluate("""() => {
const box = document.getElementById('center-stage').getBoundingClientRect();
const inlineEl = document.getElementById('img-mx-only');
const blockEl = document.getElementById('img-mx-block');
return {
mx_only_display: getComputedStyle(inlineEl).display,
mx_only_left: Math.round(inlineEl.getBoundingClientRect().left - box.left),
mx_block_display: getComputedStyle(blockEl).display,
mx_block_left: Math.round(blockEl.getBoundingClientRect().left - box.left),
mx_block_right_gap: Math.round(box.right - blockEl.getBoundingClientRect().right),
};
}""")
expected_3 = {
"mx_only_display": "inline",
"mx_only_left": 0,
"mx_block_display": "block",
"mx_block_left": 300,
"mx_block_right_gap": 300,
}
cases.append(dict(name="center_image_mx_auto_d_block", passed=(res3 == expected_3), expected=expected_3, actual=res3))
# Case 4: responsive_img_fluid_scaling
page.set_viewport_size({"width": 375, "height": 800})
narrow = page.evaluate("""() => {
const el = document.getElementById('img-fluid');
const r = el.getBoundingClientRect();
const s = getComputedStyle(el);
return { w: Math.round(r.width), h: Math.round(r.height), max_w: s.maxWidth };
}""")
page.set_viewport_size({"width": 1200, "height": 800})
wide = page.evaluate("""() => {
const r = document.getElementById('img-fluid').getBoundingClientRect();
return { w: Math.round(r.width), h: Math.round(r.height) };
}""")
actual_4 = {"viewport_375": narrow, "viewport_1200": wide}
expected_4 = {
"viewport_375": {"w": 345, "h": 173, "max_w": "100%"},
"viewport_1200": {"w": 800, "h": 400},
}
cases.append(dict(name="responsive_img_fluid_scaling", passed=(actual_4 == expected_4), expected=expected_4, actual=actual_4))
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
因为 <img> 默认为行内元素,margin: auto 无法对行内元素产生水平居中效果,必须加上 .d-block 转为块级元素;.img-fluid 设置的是 max-width: 100% 而非 width: 100%,因此只会缩小超宽图片,不会强行放大原本较小的图片。