Bootstrap5 表单浮动标签
解析 Bootstrap 5 `.form-floating` 浮动标签的 `:placeholder-shown` CSS 机制、必需 DOM 顺序与 `placeholder` 属性要求,以及 `<input>`、`<textarea>` 和 `<select>` 的实测浮动表现。
学完这一章,你能够
- 解析 Bootstrap 5 `.form-floating` 浮动标签的 `:placeholder-shown` CSS 机制、必需 DOM 顺序与 `placeholder` 属性要求,以及 `<input>`、`<textarea>` 和 `<select>` 的实测浮动表现。
浮动标签原理与必需结构要求
传统表单标签通常固定显示在输入框上方,而 Bootstrap 5 的 `.form-floating` 容器让 `<label>` 初始叠放在输入框内部,当用户点击聚焦或输入内容后平滑缩小并上浮至左上角。该效果依赖纯 CSS 兄弟选择器与 `:placeholder-shown` 伪类实现,因此必须同时满足两项硬性规则:第一,`<label>` 必须写在 `<input>` 之后;第二,`<input>` 必须声明非空 `placeholder` 属性(Bootstrap 会将其文字设为透明,仅用于触发 `:placeholder-shown` 状态切换)。本站离线 Chromium 实测:空值未聚焦时标签 `opacity: 1`、`transform: none`;聚焦后切换为 `opacity: 0.65` 且应用缩放上浮变换,输入框顶部内边距调整为 `26px`;填入 `"dev@example.com"` 并失焦后标签仍保持上浮。反之,若省略 `placeholder` 属性,`:placeholder-shown` 永不匹配,实测空输入框未聚焦时标签也会一直卡在上浮态(`opacity: 0.65`)。
多行文本框与下拉选择框的浮动表现
多行 `<textarea class="form-control" placeholder="...">` 同样支持 `.form-floating` 浮动动画(自定义高度可通过行内或外部样式设置 `height`,而非仅依赖 `rows`)。Chromium 实测空 `<textarea>` 初始 `opacity: 1`、`transform: none`,填入文本并失焦后稳定保持上浮态(`opacity: 0.65`)。
对于下拉选择框 `<select class="form-select">`,由于原生单选下拉框始终存在当前可见选项,无法在框内中央留白放置未上浮标签,因此 `.form-floating > .form-select ~ label` 规则使标签在页面初始加载时即固定缩小停留在左上角,点击或切换选项均不产生上下跳动。Chromium 实测初始与切换至选项 `"3"` 后,标签始终维持 `opacity: 0.65` 与缩放上浮变换。
运行 Bootstrap 5 浮动标签聚焦切换、缺失 placeholder 陷阱、文本框与下拉框实验
展开查看收起
"""Offline Playwright Chromium verification for Bootstrap 5 Floating Labels."""
import json
from playwright.sync_api import sync_playwright
CSS = """
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; font-size: 16px; line-height: 1.5; }
.wrap { width: 600px; }
.form-floating { position: relative; }
.form-floating > .form-control, .form-floating > .form-select {
display: block; width: 100%; height: calc(3.5rem + 2px); line-height: 1.25;
padding: 1rem 0.75rem; font-size: 1rem; border: 1px solid #ced4da; border-radius: 0.375rem;
}
.form-floating > textarea.form-control { height: 100px; }
.form-floating > label {
position: absolute; top: 0; left: 0; height: 100%; padding: 1rem 0.75rem;
pointer-events: none; border: 1px solid transparent; transform-origin: 0 0;
opacity: 1; transform: none;
}
.form-floating > .form-control::placeholder { color: transparent; }
.form-floating > .form-control:focus,
.form-floating > .form-control:not(:placeholder-shown) {
padding-top: 1.625rem; padding-bottom: 0.625rem;
}
.form-floating > .form-select { padding-top: 1.625rem; padding-bottom: 0.625rem; }
.form-floating > .form-control:focus ~ label,
.form-floating > .form-control:not(:placeholder-shown) ~ label,
.form-floating > .form-select ~ label {
opacity: 0.65;
transform: scale(0.85) translateY(-0.5rem) translateX(0.15rem);
}
"""
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": 800, "height": 600})
# Case 1: input focus and non-empty floating label transform
page.set_content(f"""<!DOCTYPE html><html><head><style>{CSS}</style></head><body>
<div class="wrap">
<div class="form-floating">
<input type="text" class="form-control" id="email" placeholder="Enter email">
<label id="lbl_email" for="email">Email</label>
</div>
<button id="other" type="button">BlurTarget</button>
</div></body></html>""")
idle = page.evaluate("""() => {
const cs = getComputedStyle(document.getElementById('lbl_email'));
return { opacity: cs.opacity, transform: cs.transform };
}""")
page.focus("#email")
focused = page.evaluate("""() => {
const cs = getComputedStyle(document.getElementById('lbl_email'));
return { opacity: cs.opacity, floated: cs.transform !== 'none', paddingTop: getComputedStyle(document.getElementById('email')).paddingTop };
}""")
page.fill("#email", "dev@example.com")
page.click("#other")
filled_blurred = page.evaluate("""() => {
const cs = getComputedStyle(document.getElementById('lbl_email'));
return { opacity: cs.opacity, floated: cs.transform !== 'none' };
}""")
act1 = {"idle": idle, "focused": focused, "filled_blurred": filled_blurred}
exp1 = {
"idle": {"opacity": "1", "transform": "none"},
"focused": {"opacity": "0.65", "floated": True, "paddingTop": "26px"},
"filled_blurred": {"opacity": "0.65", "floated": True},
}
cases.append({"name": "floating_input_focus_and_value", "expected": exp1, "actual": act1, "passed": act1 == exp1})
# Case 2: missing placeholder pitfall (:placeholder-shown does not match)
page.set_content(f"""<!DOCTYPE html><html><head><style>{CSS}</style></head><body>
<div class="wrap">
<div class="form-floating">
<input type="text" class="form-control" id="no_ph">
<label id="lbl_noph" for="no_ph">Missing Placeholder</label>
</div>
</div></body></html>""")
act2 = page.evaluate("""() => {
const cs = getComputedStyle(document.getElementById('lbl_noph'));
return { empty_unfocused_opacity: cs.opacity, stuck_floated: cs.transform !== 'none' };
}""")
exp2 = {"empty_unfocused_opacity": "0.65", "stuck_floated": True}
cases.append({"name": "floating_missing_placeholder_pitfall", "expected": exp2, "actual": act2, "passed": act2 == exp2})
# Case 3: floating textarea
page.set_content(f"""<!DOCTYPE html><html><head><style>{CSS}</style></head><body>
<div class="wrap">
<div class="form-floating">
<textarea class="form-control" id="comment" placeholder="Comment goes here"></textarea>
<label id="lbl_ta" for="comment">Comments</label>
</div>
<button id="other2" type="button">BlurTarget</button>
</div></body></html>""")
ta_idle = page.evaluate("() => ({ opacity: getComputedStyle(document.getElementById('lbl_ta')).opacity, transform: getComputedStyle(document.getElementById('lbl_ta')).transform })")
page.fill("#comment", "Great layout!")
page.click("#other2")
ta_filled = page.evaluate("() => ({ opacity: getComputedStyle(document.getElementById('lbl_ta')).opacity, floated: getComputedStyle(document.getElementById('lbl_ta')).transform !== 'none' })")
act3 = {"idle": ta_idle, "filled_blurred": ta_filled}
exp3 = {"idle": {"opacity": "1", "transform": "none"}, "filled_blurred": {"opacity": "0.65", "floated": True}}
cases.append({"name": "floating_textarea_behavior", "expected": exp3, "actual": act3, "passed": act3 == exp3})
# Case 4: floating select (always floated at top-left)
page.set_content(f"""<!DOCTYPE html><html><head><style>{CSS}</style></head><body>
<div class="wrap">
<div class="form-floating">
<select class="form-select" id="sel1">
<option value="1">1</option><option value="2">2</option><option value="3">3</option>
</select>
<label id="lbl_sel" for="sel1">Select list:</label>
</div>
</div></body></html>""")
sel_init = page.evaluate("() => ({ opacity: getComputedStyle(document.getElementById('lbl_sel')).opacity, floated: getComputedStyle(document.getElementById('lbl_sel')).transform !== 'none' })")
page.select_option("#sel1", "3")
sel_after = page.evaluate("() => ({ value: document.getElementById('sel1').value, opacity: getComputedStyle(document.getElementById('lbl_sel')).opacity, floated: getComputedStyle(document.getElementById('lbl_sel')).transform !== 'none' })")
act4 = {"initial": sel_init, "after_change": sel_after}
exp4 = {
"initial": {"opacity": "0.65", "floated": True},
"after_change": {"value": "3", "opacity": "0.65", "floated": True},
}
cases.append({"name": "floating_select_always_floated", "expected": exp4, "actual": act4, "passed": act4 == exp4})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
Bootstrap 5 使用通用兄弟选择器 `.form-control:not(:placeholder-shown) ~ label` 控制上浮,因此 `<label>` 必须作为后续兄弟节点紧随 `<input>`;同时只有存在 `placeholder` 属性时浏览器才会匹配 `:placeholder-shown`,否则空输入框也会误判为已输入并始终卡在上浮状态。