Bootstrap5 图像形状
核对 Bootstrap 5 圆角/椭圆/缩略图图像样式类、.float-start/.float-end 浮动对齐、.mx-auto.d-block 居中以及 .img-fluid 等比响应式缩放实测。
学完这一章,你能够
- 核对 Bootstrap 5 圆角/椭圆/缩略图图像样式类、.float-start/.float-end 浮动对齐、.mx-auto.d-block 居中以及 .img-fluid 等比响应式缩放实测。
圆角、椭圆与缩略图形状类
Bootstrap 5 提供三类开箱即用的图像外观修饰类:`.rounded` 为四角添加圆角;`.rounded-circle` 设置 `border-radius: 50%`(方形图呈正圆,矩形图呈椭圆);`.img-thumbnail` 添加白底、1px 浅灰边框、内边距与圆角,打造相框式缩略图。本站离线渲染内联 SVG 图像实测:`.rounded` 圆角为 `4px`(`0.25rem`),`.rounded-circle` 为 `50%`,`.img-thumbnail` 内边距 `4px`、边框 `1px rgb(222, 226, 230)`、圆角 `4px` 且背景 `rgb(255, 255, 255)`。
图片浮动对齐与水平居中
左右对齐在 Bootstrap 5 中统一使用逻辑方向类 `.float-start`(替代 BS4 的 `.float-left`)与 `.float-end`(替代 `.float-right`),外层建议配合 `.clearfix` 防止高度塌陷。本站在 `600px` 容器内实测两张 `120×80` 图片分别应用 `.float-start` 与 `.float-end`:`float` 计算值为 `left` 与 `right`,左图紧贴容器左边缘(偏移 `0px`)、右图紧贴容器右边缘(偏移 `0px`)且顶边齐平。
由于 `<img>` 默认属于行内替换元素,单独加 `margin: auto` 无法水平居中,必须组合 `.d-block`(转为块级)与 `.mx-auto`(左右自动外边距)。本站在 `600px` 容器内对 `300px` 宽图片应用 `.mx-auto.d-block` 实测:`display` 为 `block`,左右外边距与容器留白均精确等于 `150px`。
响应式图片 .img-fluid
不同终端屏幕宽度差异显著,为 `<img>` 添加 `.img-fluid` 即施加 `max-width: 100%; height: auto;`,使大图在窄容器中自动按原始宽高比等比缩小且绝不溢出,而在宽于图片固有尺寸的容器中不会被动放大失真。本站用 `800×400` 图像实测:置于 `1000px` 容器时保持原尺寸 `800×400`;置于 `400px` 窄容器时等比缩放为 `400×200`,完美保持 2:1 比例。
离线 Chromium 实测 Bootstrap 5 图像形状、.float-start/.float-end、.mx-auto.d-block 与 .img-fluid
"""Offline Playwright Chromium lab for Bootstrap 5 Chapter 08 (images)."""
import json
from playwright.sync_api import sync_playwright
BS5_CSS = """
*, *::before, *::after { box-sizing: border-box; }
html { font-size: 16px; }
body { margin: 0; }
.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-start { float: left !important; }
.float-end { float: right !important; }
.mx-auto { margin-right: auto !important; margin-left: auto !important; }
.d-block { display: block !important; }
.img-fluid { max-width: 100%; height: auto; }
.clearfix::after { display: block; clear: both; content: ""; }
"""
SVG_300 = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='300' height='200'><rect width='300' height='200' fill='%230d6efd'/></svg>"
SVG_800 = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='800' height='400'><rect width='800' height='400' fill='%23198754'/></svg>"
HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{BS5_CSS}</style></head>
<body>
<img id="img-rounded" src="{SVG_300}" class="rounded" alt="rounded">
<img id="img-circle" src="{SVG_300}" class="rounded-circle" alt="circle">
<img id="img-thumb" src="{SVG_300}" class="img-thumbnail" alt="thumb">
<div id="align-box" class="clearfix" style="width: 600px;">
<img id="img-start" src="{SVG_300}" width="120" height="80" class="float-start" alt="start">
<img id="img-end" src="{SVG_300}" width="120" height="80" class="float-end" alt="end">
</div>
<div id="center-box" style="width: 600px;">
<img id="img-center" src="{SVG_300}" width="300" height="200" class="mx-auto d-block" alt="center">
</div>
<div id="fluid-wide" style="width: 1000px;">
<img id="img-fluid-w" src="{SVG_800}" class="img-fluid" alt="fluid wide">
</div>
<div id="fluid-narrow" style="width: 400px;">
<img id="img-fluid-n" src="{SVG_800}" class="img-fluid" alt="fluid narrow">
</div>
</body>
</html>
"""
def launch_browser(pw):
try:
return pw.chromium.launch(headless=True)
except Exception:
return pw.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page(viewport={"width": 1200, "height": 900})
page.set_content(HTML_DOC)
# Case 1: .rounded, .rounded-circle, .img-thumbnail
c1 = page.evaluate("""() => {
const rd = getComputedStyle(document.getElementById('img-rounded'));
const ci = getComputedStyle(document.getElementById('img-circle'));
const th = getComputedStyle(document.getElementById('img-thumb'));
return {
rounded_radius: rd.borderRadius,
circle_radius: ci.borderRadius,
thumb: {
padding: th.paddingTop,
border_width: th.borderTopWidth,
border_color: th.borderTopColor,
radius: th.borderRadius,
bg: th.backgroundColor
}
};
}""")
exp1 = {
"rounded_radius": "4px",
"circle_radius": "50%",
"thumb": {
"padding": "4px",
"border_width": "1px",
"border_color": "rgb(222, 226, 230)",
"radius": "4px",
"bg": "rgb(255, 255, 255)",
},
}
cases.append({
"name": "image_shapes_rounded_circle_thumbnail",
"passed": c1 == exp1,
"expected": exp1,
"actual": c1,
})
# Case 2: .float-start and .float-end alignment
c2 = page.evaluate("""() => {
const box = document.getElementById('align-box').getBoundingClientRect();
const st = document.getElementById('img-start');
const en = document.getElementById('img-end');
const rs = st.getBoundingClientRect();
const re = en.getBoundingClientRect();
return {
start_float: getComputedStyle(st).float,
end_float: getComputedStyle(en).float,
start_offset_left: Math.round(rs.left - box.left),
end_offset_right: Math.round(box.right - re.right),
same_top: Math.abs(rs.top - re.top) < 1
};
}""")
exp2 = {
"start_float": "left",
"end_float": "right",
"start_offset_left": 0,
"end_offset_right": 0,
"same_top": True,
}
cases.append({
"name": "image_float_start_and_end",
"passed": c2 == exp2,
"expected": exp2,
"actual": c2,
})
# Case 3: .mx-auto.d-block centering
c3 = page.evaluate("""() => {
const box = document.getElementById('center-box').getBoundingClientRect();
const el = document.getElementById('img-center');
const r = el.getBoundingClientRect();
const cs = getComputedStyle(el);
return {
display: cs.display,
margins_x: [cs.marginLeft, cs.marginRight],
left_gap: Math.round(r.left - box.left),
right_gap: Math.round(box.right - r.right)
};
}""")
exp3 = {
"display": "block",
"margins_x": ["150px", "150px"],
"left_gap": 150,
"right_gap": 150,
}
cases.append({
"name": "image_center_mx_auto_d_block",
"passed": c3 == exp3,
"expected": exp3,
"actual": c3,
})
# Case 4: .img-fluid responsive scaling
c4 = page.evaluate("""() => {
const w = document.getElementById('img-fluid-w');
const n = document.getElementById('img-fluid-n');
const rw = w.getBoundingClientRect();
const rn = n.getBoundingClientRect();
return {
max_width: getComputedStyle(n).maxWidth,
wide_box_dims: [Math.round(rw.width), Math.round(rw.height)],
narrow_box_dims: [Math.round(rn.width), Math.round(rn.height)]
};
}""")
exp4 = {
"max_width": "100%",
"wide_box_dims": [800, 400],
"narrow_box_dims": [400, 200],
}
cases.append({
"name": "responsive_img_fluid",
"passed": c4 == exp4,
"expected": exp4,
"actual": c4,
})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对 .rounded/.rounded-circle/.img-thumbnail 样式值、600px 容器下左右贴边与 150px 居中,以及 800×400 图片在 1000px/400px 容器下保持 800×400 与等比缩至 400×200。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:f73990bad6a0f8e9ab8fa788533084c49c1502d3608cb370bcdc43ef76f39af3
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:9afff5982a8ba06081eaa2fd9e0eaff12a491a0bd531c8d959b752ee4e202b6c
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么图片居中需要同时添加 .mx-auto 和 .d-block?给一张 300px 宽的图片添加 .img-fluid 后放入 800px 容器,它会被拉伸到 800px 吗?
展开参考解答
<img> 默认是行内元素,margin: 0 auto 仅对块级元素生效,因此需 .d-block 将其设为块级;不会拉伸,因为 .img-fluid 设置的是 max-width: 100% 而非 width: 100%,图片只会在容器窄于自身宽度时等比缩小。