Skip to content

bootstrap_ref_css_forms

Bootstrap 5 中的单个表单控件会自动获得一些全局样式,旨在跨浏览器和设备提供一致的外观和体验。

默认情况下,所有带有 “.form-control” 类的文本 ,

Bootstrap 5 表单的主要注意事项:

  • 虽然 Bootstrap 对样式没有严格要求,但向
    元素添加 role="form" 可以改善依赖屏幕阅读器的用户的可访问性。
  • 将标签(labels)和表单控件包装在一个
    中,通常使用像 mb-3 (margin-bottom 3) 这样的外边距工具类来获得最佳间距。旧的 .form-group 类已不再用于此目的。
  • 向所有文本 , 类以应用 Bootstrap 的默认样式。

以下示例展示了一个简单的 Bootstrap 5 表单,包含两个输入字段、一个复选框和一个提交按钮:

<form>
<div class="mb-3">
<label for="emailInput" class="form-label">Email address:</label>
<input type="email" class="form-control" id="emailInput" aria-describedby="emailHelp">
<div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div>
</div>
<div class="mb-3">
<label for="passwordInput" class="form-label">Password:</label>
<input type="password" class="form-control" id="passwordInput">
</div>
<div class="mb-3 form-check">
<input type="checkbox" class="form-check-input" id="rememberMeCheck">
<label class="form-check-label" for="rememberMeCheck">Remember me</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<!--
实际应用: 这种结构非常适用于登录表单、联系表单或任何简单的数据输入。
常见障碍: 如何在表单元素之间获得正确的间距。Bootstrap 5 的外边距工具类(如 mb-3)解决了这个问题。
进一步阅读: 请参阅 Bootstrap 5 官方文档中关于表单的部分,了解更高级的布局和组件: https://getbootstrap.com/docs/5.3/forms/overview/
-->

Bootstrap 5 提供了灵活的方式来构建表单。以下是一些常见的布局方法:

类/技术 描述 示例

内联表单 (Inline Forms) (使用 Flexbox 或 Grid) 创建元素水平布局的表单。这通过使用 Bootstrap 的 flexbox 工具类(例如,d-flex、align-items-center、me-2)或网格系统(row、col)来实现。这取代了旧的 .form-inline 类。

Flexbox 示例:

<form class="d-flex align-items-center">
<label for="inlineName" class="visually-hidden">Name</label>
<input type="text" class="form-control me-2" id="inlineName" placeholder="Jane Doe">
<button type="submit" class="btn btn-primary">Submit</button>
</form>

Grid 示例 (适用于更复杂的内联表单):

<form class="row gx-3 gy-2 align-items-center">
<div class="col-auto">
<label class="visually-hidden" for="specificSizeInputName">Name</label>
<input type="text" class="form-control" id="specificSizeInputName" placeholder="Jane Doe">
</div>
<div class="col-auto">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>

水平表单 (Horizontal Forms) (使用 Grid) 使标签和表单控件并排对齐。这通过使用 Bootstrap 的网格系统(.row、.col-*、.col-form-label)来实现。这取代了旧的 .form-horizontal 类。

示例:

<form>
<div class="row mb-3">
<label for="inputEmail3" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="inputEmail3">
</div>
</div>
<div class="row mb-3">
<label for="inputPassword3" class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword3">
</div>
</div>
<button type="submit" class="btn btn-primary">Sign in</button>
</form>