Skip to content

Bootstrap 速查表

基于 CSS 和 JavaScript 构建的强大、可扩展且功能丰富的前端工具包。

01

入门基础

引入 Bootstrap

通过 CDN 引入 Bootstrap 可以快速开始——CSS 放在 <head> 中,JS 包(包含 Popper)放在 </body> 之前。bundle.min.js 包含 Popper,用于工具提示/下拉菜单/弹出框。使用 npm 时,在入口文件中导入 CSS 和 JS。Bootstrap 5 移除了 jQuery 依赖——所有组件都使用原生 JavaScript 工作。

bootstrap
<!-- CSS only (in <head>) -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">

<!-- JS bundle (before </body>) -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>

<!-- or install via npm -->
<!-- npm install [email protected] -->

<!-- import in JS -->
// import 'bootstrap/dist/css/bootstrap.min.css'
// import 'bootstrap'  // imports all JS

容器

容器是最基本的布局元素——它们居中内容并添加水平内边距。.container 在每个断点处为固定宽度(max-width 变化);.container-fluid 始终为 100% 宽度。响应式容器(container-sm/md/lg/xl/xxl)在指定断点之前为 100% 宽度,之后变为固定宽度。大多数布局使用 .container;全宽应用使用 .container-fluid。

bootstrap
<!-- fixed-width container (responsive breakpoints) -->
<div class="container">
  <!-- content centered with max-width -->
</div>

<!-- full-width container -->
<div class="container-fluid">
  <!-- spans entire viewport width -->
</div>

<!-- responsive containers (max-width at breakpoint) -->
<div class="container-sm">  <!-- 100% until sm, then fixed -->
<div class="container-md">
<div class="container-xl">

<!-- 100% wide until the breakpoint, then max-width applied -->
<div class="container-xxl">

响应式断点

Bootstrap 使用移动优先的 min-width 媒体查询系统。共有 6 个断点:xs(默认)、sm(576px)、md(768px)、lg(992px)、xl(1200px)、xxl(1400px)。col-md-6 等类在 md 及以上断点生效。要在断点处显示/隐藏元素,使用 d-none(display:none)和 d-{breakpoint}-block。这种移动优先方法意味着先为小屏幕设计,再为大屏幕添加复杂性。

bootstrap
/* Bootstrap 5 breakpoints (min-width, mobile-first) */
/* xs: <576px  (default, no media query needed) */
/* sm: >=576px */
/* md: >=768px */
/* lg: >=992px */
/* xl: >=1200px */
/* xxl: >=1400px */

<!-- classes apply AT and ABOVE the breakpoint -->
<div class="col-12 col-md-6 col-lg-4">
  <!-- full width on mobile, half on md, third on lg -->
</div>

<!-- hidden/visible at breakpoints -->
<div class="d-none d-md-block">  <!-- hidden below md -->
<div class="d-block d-md-none">  <!-- visible below md only -->

Reboot 与基础样式

Reboot 是 Bootstrap 的 CSS 重置——它使用 rem 单位(根 em,基于 html 的 16px 字体大小)规范化浏览器样式。所有元素都设置了 box-sizing: border-box。标题、段落、列表、表格和链接都有合理的默认值。Reboot 移除了标题和列表的上边距,将其设为 0。这在 Bootstrap 组件层叠之前提供了跨浏览器的一致基线。

bootstrap
<!-- Reboot normalizes styles: box-sizing, margins, etc. -->
<!-- body gets: font-family, font-size (1rem), line-height (1.5), color -->

<!-- headings use rem units, margin-top removed -->
<h1>Heading 1 (2.5rem)</h1>
<h2>Heading 2 (2rem)</h2>

<!-- links get color and underline on hover -->
<a href="#">Default link</a>

<!-- tables get basic styling -->
<table class="table">...</table>

<!-- <ul>/<ol> have padding-left removed -->
<ul>
  <li>Item</li>
</ul>

使用 CSS 变量自定义

Bootstrap 5 暴露了数百个以 --bs- 为前缀的 CSS 自定义属性(变量)。在 :root 中覆盖它们可以全局主题化你的网站。深色模式通过 <html> 元素上的 data-bs-theme='dark' 内置支持,它会交换一组变量。这使得主题化比旧的 Sass 变量方法容易得多——你可以用纯 CSS 更改颜色、字体、间距和圆角,无需构建步骤。

bootstrap
:root {
  /* override Bootstrap's CSS variables */
  --bs-primary: #0d6efd;
  --bs-body-bg: #ffffff;
  --bs-body-color: #212529;
  --bs-font-sans-serif: 'Inter', system-ui, sans-serif;
  --bs-border-radius: 0.375rem;
}

/* dark mode via data attribute */
[data-bs-theme="dark"] {
  --bs-body-bg: #212529;
  --bs-body-color: #f8f9fa;
}

<!-- use in HTML -->
<div style="background: var(--bs-primary); color: var(--bs-white);">
  Custom styled
</div>
02

布局基础

行与列

.row 是一个 flex 容器(display: flex),带有负水平边距以抵消列内边距。直接的 .col 子元素等分填充行。指定 col-{1-12} 获得固定比例(共 12 列)。不带数字时,.col 取相等的剩余空间。12 列网格是 Bootstrap 布局的核心——组合 col-{n} 和自动 .col 实现灵活布局。

bootstrap
<!-- .row creates a flex container with negative margins -->
<!-- .col children flex equally -->
<div class="container">
  <div class="row">
    <div class="col">Column 1</div>
    <div class="col">Column 2</div>
    <div class="col">Column 3</div>
  </div>
  <!-- 3 equal columns -->
</div>

<!-- sized columns -->
<div class="row">
  <div class="col-8">8/12 width</div>
  <div class="col-4">4/12 width</div>
</div>

<!-- auto + sized -->
<div class="row">
  <div class="col">auto width (content-based)</div>
  <div class="col-6">exactly half</div>
  <div class="col">auto width</div>
</div>

间距(列间距)

间距(Gutters)是列之间的内边距,由 g-* 类控制(g-0 到 g-5)。g-0 移除所有间距(边缘到边缘的列)。g-3 是默认值。间距在水平(列之间)和垂直(列换行时行之间)都起作用。使用响应式变体(g-2 g-md-4)在不同断点获得不同间距。间距系统取代了旧的仅水平内边距方法。

bootstrap
<!-- default gutters (1.5rem padding on each side of columns) -->
<div class="row">
  <div class="col-6">A</div>
  <div class="col-6">B</div>
</div>

<!-- remove gutters -->
<div class="row g-0">
  <div class="col-6">A</div>
  <div class="col-6">B</div>
</div>

<!-- custom gutter sizes: g-0 to g-5 -->
<div class="row g-3">
  <div class="col-6">A</div>
  <div class="col-6">B</div>
</div>

<!-- responsive gutters -->
<div class="row g-2 g-md-4">
  <div class="col-6">A</div>
  <div class="col-6">B</div>
</div>

<!-- vertical gutters (row spacing) -->
<div class="row g-3">
  <div class="col-12">Row 1</div>
  <div class="col-12">Row 2 (g-3 gap above)</div>
</div>

列换行与对齐

当列总数超过 12 时,列会换行到新行。使用行上的 align-items-* 控制垂直对齐(start/center/end)。使用 justify-content-* 控制水平分布(start/center/end/between/around/evenly)。这些底层使用 flexbox。换行是自动的——无需显式的行分隔。这使得仅用 col-* 类就能轻松实现类似瀑布流的布局。

bootstrap
<!-- columns wrap when they exceed 12 total -->
<div class="row">
  <div class="col-9">9 cols</div>
  <div class="col-4">4 cols → wraps to next line (9+4=13)</div>
  <div class="col-6">6 cols (new line)</div>
</div>

<!-- vertical alignment -->
<div class="row align-items-center">
  <div class="col">Vertically centered</div>
</div>

<!-- options: align-items-start, -center, -end -->
<div class="row align-items-end">...</div>

<!-- horizontal alignment -->
<div class="row justify-content-center">
  <div class="col-6">Centered horizontally</div>
</div>

<!-- options: justify-content-start, -center, -end, -between, -around, -evenly -->

列排序

排序类在不改变 HTML 的情况下视觉重排列。order-first、order-{1-5}、order-last 提供 7 个级别。使用响应式变体(order-md-first)在断点处改变顺序——对 SEO 很有用(重要内容在 HTML 中靠前,但在移动端显示不同)。偏移量(offset-md-4)添加左边距将列向右推——用于居中或缩进。两者都依赖 flexbox 的 order 和 margin 工具类。

bootstrap
<!-- order classes: order-first, order-{1-5}, order-last -->
<div class="row">
  <div class="col order-2">First in HTML, second visually</div>
  <div class="col order-1">Second in HTML, first visually</div>
  <div class="col order-3">Third in both</div>
</div>

<!-- responsive ordering -->
<div class="row">
  <div class="col order-last order-md-first">
    Last on mobile, first on desktop
  </div>
  <div class="col">Normal</div>
</div>

<!-- column offset (push right) -->
<div class="row">
  <div class="col-md-4 offset-md-4">Centered (offset 4)</div>
</div>

<!-- offset responsive -->
<div class="col-md-4 offset-md-2 offset-lg-4">...</div>

Z-Index 与层叠

Bootstrap 使用 z-index 比例进行层叠:z-1、z-2、z-3(以及负值 z-n0、z-n1、z-n2)。模态框、下拉菜单和工具提示等组件具有更高的内置 z-index 值(1000-1080)。要让 z-index 生效,元素需要 position(relative、absolute、fixed 或 sticky)。避免使用任意 z-index 值——使用 Bootstrap 的比例保持一致性。层叠顺序设计为模态框始终在下拉菜单之上,下拉菜单在导航栏之上。

bootstrap
/* Bootstrap's z-index scale */
/* z-1 to z-3, plus z-n0, z-n1, z-n2 for negatives */

<div class="z-3 position-relative">High z-index</div>
<div class="z-1 position-relative">Low z-index</div>

<!-- components have built-in z-index: -->
/* dropdown: 1000 */
/* sticky: 1020 */
/* fixed: 1030 */
/* modal-backdrop: 1050 */
/* modal: 1055 */
/* popover: 1070 */
/* tooltip: 1080 */

<!-- use position utilities for stacking context -->
<div class="position-relative z-3">
  Needs position for z-index to apply
</div>
03

网格系统

基础网格

Bootstrap 的网格是一个 12 列系统。col-{1-12} 指定元素跨越的 12 列中的多少列。col-12 = 全宽,col-6 = 一半,col-4 = 三分之一,col-3 = 四分之一。行内列的总和应为 12(或更少——剩余空间会被分配)。不带数字时,.col 等分剩余空间。网格使用 flexbox——行是 flex 容器,列是 flex 项目。

bootstrap
<!-- 12-column grid -->
<div class="container">
  <div class="row">
    <div class="col-12">Full width (12/12)</div>
  </div>
  <div class="row">
    <div class="col-6">Half (6/12)</div>
    <div class="col-6">Half (6/12)</div>
  </div>
  <div class="row">
    <div class="col-4">Third (4/12)</div>
    <div class="col-4">Third (4/12)</div>
    <div class="col-4">Third (4/12)</div>
  </div>
  <div class="row">
    <div class="col-3">Quarter (3/12)</div>
    <div class="col-9">Three-quarters (9/12)</div>
  </div>
</div>

响应式列

响应式列类(col-sm-*、col-md-*、col-lg-*、col-xl-*、col-xxl-*)在该断点及之上生效(移动优先)。最小的适用类优先。col-12 col-md-6 col-lg-4 表示:移动端全宽,平板端一半,桌面端三分之一。row-cols-* 设置每个断点每行等宽列的数量——当所有列宽度相同时,比在每个子元素上指定 col-* 更简洁。

bootstrap
<!-- different widths at different breakpoints -->
<div class="row">
  <!-- full on mobile, half on md, third on lg -->
  <div class="col-12 col-md-6 col-lg-4">Card 1</div>
  <div class="col-12 col-md-6 col-lg-4">Card 2</div>
  <div class="col-12 col-md-6 col-lg-4">Card 3</div>
</div>

<!-- mobile-first: base class applies to all, -->
<!-- larger breakpoints override -->
<div class="col-12 col-sm-6 col-md-4 col-lg-3 col-xl-2">
  1 per row on xs, 2 on sm, 3 on md, 4 on lg, 6 on xl
</div>

<!-- equal-width columns at breakpoint -->
<div class="row row-cols-1 row-cols-md-2 row-cols-lg-3">
  <div class="col">Auto-width card</div>
  <div class="col">Auto-width card</div>
  <div class="col">Auto-width card</div>
</div>

嵌套列

要嵌套网格,在 .col 内放置 .row——嵌套的行在父列宽度内创建新的 12 列上下文。嵌套列(col-4、col-8)分割父元素宽度,而非整个页面。嵌套对于带子部分的复杂布局(如侧边栏)必不可少。保持嵌套较浅(最多 2-3 层)以避免列过窄并保持可读性。

bootstrap
<!-- nest a row inside a column -->
<div class="row">
  <div class="col-6">
    <!-- outer column -->
    <h3>Left half</h3>
    <!-- nested row: new 12-column context -->
    <div class="row">
      <div class="col-4">Nested 1/3 of parent</div>
      <div class="col-8">Nested 2/3 of parent</div>
    </div>
  </div>
  <div class="col-6">
    <h3>Right half</h3>
  </div>
</div>

<!-- the nested row creates a new 12-col grid -->
<!-- within the parent column's width -->

列偏移与边距

offset-{breakpoint}-{n} 添加 n 列的左边距,用于居中或缩进。col-md-4 上的 offset-md-4 使其居中(4 + 4 + 4 = 12)。更简单的居中方式是使用 mx-auto(margin: 0 auto),无论列数多少都有效。响应式偏移(offset-sm-2 offset-md-0)允许在移动端缩进但在桌面端不缩进。偏移比空占位列更简洁。

bootstrap
<!-- offset: add left margin (empty columns) -->
<div class="row">
  <div class="col-md-4 offset-md-4">
    Centered (4 + 4 offset each side = 12)
  </div>
</div>

<!-- offset only on one side -->
<div class="row">
  <div class="col-md-6 offset-md-3">
    Centered with more left space
  </div>
</div>

<!-- responsive offset -->
<div class="row">
  <div class="col-sm-8 offset-sm-2 offset-md-0 col-md-12">
    Offset on mobile, none on desktop
  </div>
</div>

<!-- margin utilities for auto centering -->
<div class="row">
  <div class="col-md-6 mx-auto">
    Auto-centered (margin: 0 auto)
  </div>
</div>

行列与自动布局

row-cols-{n} 设置每行等宽列的数量——当所有列宽度相同时,比在每个子元素上添加 col-* 更简洁。row-cols-2 表示每行 2 列;项目自动换行。响应式变体(row-cols-1 row-cols-md-3)在断点处改变数量。普通 .col(无数字)使列等分空间。卡片网格使用 row-cols;需要特定比例时使用 col-{n}。

bootstrap
<!-- row-cols: set number of columns per row -->
<div class="row row-cols-2">
  <div class="col">Item 1</div>
  <div class="col">Item 2</div>
  <div class="col">Item 3</div>  <!-- wraps to new row -->
  <div class="col">Item 4</div>
</div>
<!-- 2 per row automatically -->

<!-- responsive row-cols -->
<div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 row-cols-lg-4">
  <div class="col">Card</div>
  <div class="col">Card</div>
  <div class="col">Card</div>
  <div class="col">Card</div>
</div>

<!-- auto-fit columns: .col without number -->
<div class="row">
  <div class="col">Equal</div>
  <div class="col">Equal</div>
  <div class="col">Equal</div>
</div>
<!-- each takes 1/3, regardless of content -->
04

排版

标题与展示标题

Bootstrap 使用基于 rem 的尺寸样式化 h1-h6(h1 = 2.5rem,h6 = 1rem)。.h1-.h6 类将标题样式应用于任何元素。展示标题(display-1 到 display-6)更大更细——用于英雄区域。.lead 使段落稍大更轻——通常用于第一段。标题默认没有上边距(Reboot 移除了它)以避免布局间隙。

bootstrap
<!-- standard headings (h1-h6) -->
<h1>h1 heading</h1>
<h2>h2 heading</h2>
<h3>h3 heading</h3>

<!-- heading classes for matching styles -->
<p class="h1">Looks like h1</p>
<p class="h2">Looks like h2</p>

<!-- display headings (larger, thinner) -->
<h1 class="display-1">Display 1</h1>
<h1 class="display-2">Display 2</h1>
<h1 class="display-3">Display 3</h1>
<h1 class="display-4">Display 4</h1>
<h1 class="display-5">Display 5</h1>
<h1 class="display-6">Display 6</h1>

<!-- lead paragraph -->
<p class="lead">This is a lead paragraph.</p>

行内文本元素

Bootstrap 样式化语义 HTML 元素:<mark>(高亮)、<del>/<s>(删除线)、<ins>/<u>(下划线)、<small>(小字)。文本工具类提供样式:text-uppercase/lowercase/capitalize、fw-bold/light/normal、fst-italic、text-muted(灰色)。text-decoration-underline/line-through 控制下划线。这些工具类优于内联样式以保持一致性。

bootstrap
<!-- text styling -->
<p>You can use <mark>highlight</mark> text.</p>
<p><del>Deleted</del> and <s>strikethrough</s> text.</p>
<p><ins>Inserted</ins> and <u>underline</u> text.</p>
<p><small>Small text</small> for fine print.</p>
<p><strong>Bold</strong> and <em>italic</em> text.</p>

<!-- text utilities -->
<p class="text-decoration-underline">Underlined</p>
<p class="text-decoration-line-through">Line through</p>
<p class="text-lowercase">lowercase text</p>
<p class="text-uppercase">UPPERCASE TEXT</p>
<p class="text-capitalize">Capitalized Text</p>
<p class="fw-bold">Font weight bold</p>
<p class="fw-light">Font weight light</p>
<p class="fst-italic">Font style italic</p>
<p class="text-muted">Muted/gray text</p>

列表

list-unstyled 移除默认列表样式(项目符号和左内边距)——用于导航菜单。list-inline 使列表项内联显示(用于标签云、面包屑)。描述列表(dl/dt/dd)通过 row 类获得水平布局——dt 在左,dd 在右,通过网格对齐。Bootstrap 中的列表有 margin-top: 0 和 margin-bottom: 1rem 以保持一致的间距。

bootstrap
<!-- unordered list -->
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
</ul>

<!-- unstyled list (no bullets, no padding) -->
<ul class="list-unstyled">
  <li>No bullets</li>
  <li>No left padding</li>
</ul>

<!-- inline list -->
<ul class="list-inline">
  <li class="list-inline-item">Inline 1</li>
  <li class="list-inline-item">Inline 2</li>
  <li class="list-inline-item">Inline 3</li>
</ul>

<!-- description list -->
<dl>
  <dt>Term</dt>
  <dd>Definition</dd>
</dl>

<!-- horizontal description list -->
<dl class="row">
  <dt class="col-sm-3">Term</dt>
  <dd class="col-sm-9">Definition</dd>
</dl>

引用与代码

引用使用 <figure>/<blockquote>/<figcaption> 结构以获得语义。blockquote-footer 样式化引用来源。代码样式:<code> 用于行内代码,<pre><code> 用于代码块,<kbd> 用于键盘按键,<var> 用于变量。代码中的尖括号始终要 HTML 转义(< 用 &lt;)。引用可以用 text-center/text-end 对齐。kbd 样式使按键具有键盘式外观。

bootstrap
<!-- blockquote with source -->
<figure>
  <blockquote class="blockquote">
    <p>A well-known quote.</p>
  </blockquote>
  <figcaption class="blockquote-footer">
    Someone famous in <cite title="Source Title">Source Title</cite>
  </figcaption>
</figure>

<!-- blockquote alignment -->
<blockquote class="blockquote text-center">Centered</blockquote>
<blockquote class="blockquote text-end">Right-aligned</blockquote>

<!-- inline code -->
<p>Use <code>&lt;section&gt;</code> tag.</p>

<!-- code block -->
<pre><code>&lt;div class="container"&gt;
  Hello
&lt;/div&gt;
</code></pre>

<!-- variables -->
<var>y</var> = <var>mx</var> + <var>b</var>

<!-- keyboard input -->
<kbd>Ctrl</kbd> + <kbd>C</kbd>

文本对齐与换行

文本对齐:text-start/center/end(Bootstrap 5 将 left/right 重命名为 start/end 以支持 RTL)。响应式变体(text-md-start)在断点处改变对齐。text-nowrap 防止换行;text-truncate 为溢出添加省略号(需要 max-width 或受限容器)。text-break 断开长单词。lh-* 控制行高。这些工具类无需自定义 CSS 即可处理文本流。

bootstrap
<!-- text alignment -->
<p class="text-start">Left aligned (default)</p>
<p class="text-center">Center aligned</p>
<p class="text-end">Right aligned</p>

<!-- responsive alignment -->
<p class="text-center text-md-start">
  Center on mobile, left on md+
</p>

<!-- text wrapping -->
<div class="text-wrap">This text wraps.</div>
<div class="text-nowrap">This text doesn't wrap.</div>

<!-- truncate with ellipsis -->
<div class="text-truncate" style="max-width: 200px;">
  This long text will be truncated with an ellipsis...
</div>

<!-- word break -->
<p class="text-break">verylongwordwithoutspaces</p>

<!-- line height -->
<p class="lh-1">Line height 1</p>
<p class="lh-sm">Line height small</p>
<p class="lh-base">Line height base (default)</p>
<p class="lh-lg">Line height large</p>
05

表格

基础表格

.table 类添加内边距、边框和水平分隔线。表头使用 <thead>,数据使用 <tbody>。表头 <th> 上的 scope='col' 和行 <th> 上的 scope='row' 提高了屏幕阅读器的可访问性。表格是可选的——没有 .table,你会得到无样式的 HTML 表格。始终使用语义表格元素(thead、tbody、th、tr、td)以确保可访问性。

bootstrap
<!-- basic table with styling -->
<table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Name</th>
      <th scope="col">Email</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">1</th>
      <td>Alice</td>
      <td>[email protected]</td>
    </tr>
    <tr>
      <th scope="row">2</th>
      <td>Bob</td>
      <td>[email protected]</td>
    </tr>
  </tbody>
</table>

表格变体与条纹

表格修饰符:table-striped(交替行颜色)、table-bordered(所有边框)、table-borderless(无边框)、table-hover(悬停行高亮)、table-sm(紧凑内边距)、table-dark(深色主题)。这些可以组合使用:table table-striped table-hover。深色变体反转颜色用于深色背景。table-sm 将单元格内边距减半以获得更密集的数据显示。

bootstrap
<!-- striped rows -->
<table class="table table-striped">
  <!-- alternating background colors -->
</table>

<!-- bordered table -->
<table class="table table-bordered">
  <!-- borders on all sides -->
</table>

<!-- borderless table -->
<table class="table table-borderless">
  <!-- no borders -->
</table>

<!-- hoverable rows -->
<table class="table table-hover">
  <!-- row highlights on hover -->
</table>

<!-- small table -->
<table class="table table-sm">
  <!-- condensed padding -->
</table>

<!-- dark table -->
<table class="table table-dark">
  <!-- dark background -->
</table>

表格颜色

将上下文类应用于 <tr> 或 <td>:table-primary、table-success、table-danger、table-warning、table-info、table-secondary、table-light、table-dark、table-active。这些添加了细微的背景色调用于状态指示。在深色表格上,相同的类提供较浅的变体。少量使用以表示有意义的状态(success 表示完成,danger 表示错误)而非装饰。

bootstrap
<!-- contextual row/cell colors -->
<table class="table">
  <thead>
    <tr class="table-primary"><th>Primary header</th></tr>
  </thead>
  <tbody>
    <tr class="table-success">
      <td>Success row (green)</td>
    </tr>
    <tr class="table-danger">
      <td>Danger row (red)</td>
    </tr>
    <tr class="table-warning">
      <td>Warning row (yellow)</td>
    </tr>
    <tr class="table-info">
      <td>Info row (cyan)</td>
    </tr>
    <!-- individual cells -->
    <tr>
      <td class="table-active">Active cell</td>
      <td>Normal cell</td>
    </tr>
  </tbody>
</table>

响应式表格

将表格包装在 .table-responsive 中以在小屏幕上启用水平滚动(防止布局破坏)。table-responsive-sm/md/lg/xl/xxl 仅在该断点以下滚动——表格在大屏幕上正常显示。没有响应式包装,宽表格会溢出其容器。包装 div 是必需的,因为 overflow 不能直接应用于 <table>。对于多列表格始终使用此功能。

bootstrap
<!-- responsive table (horizontal scroll on small screens) -->
<div class="table-responsive">
  <table class="table">
    <!-- scrolls horizontally on small screens -->
    <thead>...</thead>
    <tbody>...</tbody>
  </table>
</div>

<!-- responsive at specific breakpoints -->
<div class="table-responsive-sm">
  <!-- scrolls below sm -->
</div>
<div class="table-responsive-md">
  <!-- scrolls below md -->
</div>
<div class="table-responsive-lg">
  <!-- scrolls below lg -->
</div>

<!-- always scrollable -->
<div class="table-responsive">...</div>

表格组与标题

caption-top 将标题移到表格上方(默认在下方)。标题提高了屏幕阅读器的可访问性。用 table-light/table-dark 分别样式化 thead/tbody/tfoot。垂直对齐:align-top、align-middle、align-bottom 应用于单元格或行——当单元格内容高度不同时很有用。tfoot 元素默认样式类似 thead 但可自定义。

bootstrap
<!-- caption (accessibility, shown below table by default) -->
<table class="table caption-top">
  <caption>List of users</caption>
  <thead>
    <tr><th>#</th><th>Name</th></tr>
  </thead>
  <tbody>
    <tr><td>1</td><td>Alice</td></tr>
  </tbody>
</table>

<!-- table groups for styling -->
<table class="table">
  <thead class="table-light">
    <tr><th>Light header</th></tr>
  </thead>
  <tbody>
    <tr><td>Body</td></tr>
  </tbody>
  <tfoot class="table-dark">
    <tr><td>Dark footer</td></tr>
  </tfoot>
</table>

<!-- vertically aligned cells -->
<tr class="align-middle">
  <td class="align-top">Top</td>
  <td class="align-middle">Middle</td>
  <td class="align-bottom">Bottom</td>
</tr>
06

表单

表单控件

form-control 样式化文本输入框、文本域和文件输入。form-select 样式化下拉菜单。始终将输入框与 <label> 元素配对(for/id 匹配)以确保可访问性。form-label 添加适当的间距。disabled 防止交互;readonly 显示值但不可编辑。mb-3(margin-bottom)在表单组之间添加间距。.form-control 类应用一致的高度、内边距和焦点样式。

bootstrap
<!-- text input -->
<div class="mb-3">
  <label for="email" class="form-label">Email</label>
  <input type="email" class="form-control" id="email" placeholder="Enter email">
</div>

<!-- textarea -->
<div class="mb-3">
  <label for="bio" class="form-label">Bio</label>
  <textarea class="form-control" id="bio" rows="3"></textarea>
</div>

<!-- select -->
<select class="form-select" aria-label="Default select">
  <option selected>Open this select menu</option>
  <option value="1">One</option>
  <option value="2">Two</option>
</select>

<!-- disabled -->
<input class="form-control" type="text" placeholder="Disabled" disabled>
<input class="form-control" type="text" value="Readonly" readonly>

表单网格与布局

使用网格系统(row/col)布局表单。对于水平表单,将 col-form-label 与 col-* 配合使用以对齐标签/输入。row-cols-lg-auto 使表单元素在大屏幕上按内容尺寸调整(内联表单)。align-items-center 垂直对齐标签和输入。网格在不同断点精确控制表单布局,无需自定义 CSS。

bootstrap
<!-- form using grid -->
<div class="row mb-3">
  <label for="name" class="col-sm-2 col-form-label">Name</label>
  <div class="col-sm-10">
    <input type="text" class="form-control" id="name">
  </div>
</div>

<!-- inline form -->
<form class="row row-cols-lg-auto g-3 align-items-center">
  <div class="col">
    <input class="form-control" placeholder="Email">
  </div>
  <div class="col">
    <input class="form-control" placeholder="Password">
  </div>
  <div class="col">
    <button type="submit" class="btn btn-primary">Sign in</button>
  </div>
</form>

<!-- horizontal form with column sizing -->
<form>
  <div class="row mb-3">
    <label class="col-2 col-form-label">Email</label>
    <div class="col-10">
      <input class="form-control" type="email">
    </div>
  </div>
</form>

输入组

输入组使用 input-group-text 在输入框前后添加文本/按钮。常用于 @ 用户名、$ 货币、.00 小数或搜索按钮。input-group 包装器使附加内容和输入框显示为一个连接的控件。多个输入框可以共享一个附加内容。输入组内的按钮使用 btn-outline-* 获得连接的外观。不要将输入组与 form-floating 混用。

bootstrap
<!-- prepend text -->
<div class="input-group mb-3">
  <span class="input-group-text">@</span>
  <input type="text" class="form-control" placeholder="Username">
</div>

<!-- append text -->
<div class="input-group mb-3">
  <input type="text" class="form-control" placeholder="Recipient's username">
  <span class="input-group-text">@example.com</span>
</div>

<!-- prepend + append -->
<div class="input-group mb-3">
  <span class="input-group-text">$</span>
  <input type="text" class="form-control">
  <span class="input-group-text">.00</span>
</div>

<!-- with button -->
<div class="input-group mb-3">
  <input type="text" class="form-control" placeholder="Search">
  <button class="btn btn-outline-secondary" type="button">Go</button>
</div>

<!-- multiple inputs -->
<div class="input-group">
  <span class="input-group-text">First and last name</span>
  <input type="text" class="form-control">
  <input type="text" class="form-control">
</div>

浮动标签

浮动标签在字段获得焦点或有内容时,将标签从输入框内部动画移动到上方。HTML 中标签必须在输入框之后。placeholder 属性是必需的(即使为空)才能实现浮动行为。此模式节省空间且看起来现代。不要与 input-group 组合使用。浮动标签适用于输入框、文本域和选择框。它们是传统标签的简洁替代方案,适合紧凑表单。

bootstrap
<!-- floating label (label floats up when focused/filled) -->
<div class="form-floating mb-3">
  <input type="email" class="form-control" id="floatingInput" placeholder="[email protected]">
  <label for="floatingInput">Email address</label>
</div>

<!-- floating textarea -->
<div class="form-floating">
  <textarea class="form-control" id="floatingTextarea" placeholder="Leave a comment"></textarea>
  <label for="floatingTextarea">Comments</label>
</div>

<!-- floating select -->
<div class="form-floating mb-3">
  <select class="form-select" id="floatingSelect">
    <option selected>Open this select menu</option>
    <option value="1">One</option>
  </select>
  <label for="floatingSelect">Works with selects</label>
</div>

<!-- note: placeholder is REQUIRED for floating labels -->
<!-- the placeholder="..." must be present -->

表单验证

Bootstrap 提供 is-valid 和 is-invalid 类用于验证样式,valid-feedback 和 invalid-feedback 用于消息。表单上的 needs-validation 类结合 novalidate(禁用浏览器工具提示),允许你使用 Bootstrap 的验证 UI 和自定义 JS。提交时,添加 was-validated 显示所有验证状态。这适用于 HTML5 约束(required、pattern、type)或自定义服务端验证。

bootstrap
<!-- server-side validation classes -->
<div class="mb-3">
  <label for="username" class="form-label">Username</label>
  <input type="text" class="form-control is-valid" id="username" value="valid_user">
  <div class="valid-feedback">Looks good!</div>
</div>

<div class="mb-3">
  <label for="email" class="form-label">Email</label>
  <input type="email" class="form-control is-invalid" id="email">
  <div class="invalid-feedback">Please enter a valid email.</div>
</div>

<!-- no validate on form to disable browser validation -->
<form class="needs-validation" novalidate>
  <div class="mb-3">
    <input type="text" class="form-control" required>
    <div class="invalid-feedback">This field is required.</div>
  </div>
  <button class="btn btn-primary" type="submit">Submit</button>
</form>

<!-- JS: form.classList.add('was-validated') on submit -->
07

按钮

按钮变体

btn 是基础按钮类;btn-{color} 设置变体。实心按钮有彩色背景和白色文本。轮廓按钮(btn-outline-*)有透明背景和彩色文本/边框——适合次要操作。btn-link 使按钮看起来像链接。有意义地选择颜色:success 用于确认,danger 用于删除,warning 用于警告。不要仅使用颜色传达含义——包含文本。

bootstrap
<!-- solid buttons -->
<button type="button" class="btn btn-primary">Primary</button>
<button type="button" class="btn btn-secondary">Secondary</button>
<button type="button" class="btn btn-success">Success</button>
<button type="button" class="btn btn-danger">Danger</button>
<button type="button" class="btn btn-warning">Warning</button>
<button type="button" class="btn btn-info">Info</button>
<button type="button" class="btn btn-light">Light</button>
<button type="button" class="btn btn-dark">Dark</button>

<!-- link-styled button -->
<button type="button" class="btn btn-link">Link</button>

<!-- outline buttons (transparent bg, colored border) -->
<button type="button" class="btn btn-outline-primary">Outline Primary</button>
<button type="button" class="btn btn-outline-danger">Outline Danger</button>

按钮尺寸与状态

按钮尺寸:btn-lg、默认、btn-sm。disabled 属性(<button> 上)或 .disabled 类(<a> 上或无法使用属性时)使按钮变灰。.active 添加按下外观。全宽按钮使用 d-grid gap-2(使按钮堆叠并填满宽度)。d-md-block 在 md 断点恢复为内联——适用于移动端全宽、桌面端自动。.disabled 类还设置 pointer-events: none。

bootstrap
<!-- sizes -->
<button class="btn btn-primary btn-lg">Large</button>
<button class="btn btn-primary">Default</button>
<button class="btn btn-primary btn-sm">Small</button>

<!-- disabled state -->
<button class="btn btn-primary" disabled>Disabled</button>
<!-- or -->
<button class="btn btn-primary disabled">Disabled (aria)</button>

<!-- active/pressed state -->
<button class="btn btn-primary active" aria-pressed="true">Active</button>

<!-- full-width block button -->
<div class="d-grid gap-2">
  <button class="btn btn-primary">Block button</button>
  <button class="btn btn-secondary">Another</button>
</div>

<!-- responsive block buttons -->
<div class="d-grid gap-2 d-md-block">
  <button class="btn btn-primary">Full on mobile, auto on md+</button>
</div>

按钮组

btn-group 将按钮水平分组,边缘连接。btn-toolbar 组合多个组并添加间距。btn-group-vertical 垂直堆叠按钮。始终添加 role='group' 和 aria-label 以确保可访问性。尺寸类(btn-group-lg/sm)应用于组内所有按钮。按钮组是工具栏、分段控件和分页类 UI 的基础。

bootstrap
<!-- basic button group -->
<div class="btn-group" role="group" aria-label="Basic example">
  <button type="button" class="btn btn-outline-primary">Left</button>
  <button type="button" class="btn btn-outline-primary">Middle</button>
  <button type="button" class="btn btn-outline-primary">Right</button>
</div>

<!-- button toolbar (groups of groups) -->
<div class="btn-toolbar" role="toolbar" aria-label="Toolbar">
  <div class="btn-group me-2" role="group">
    <button class="btn btn-outline-secondary">1</button>
    <button class="btn btn-outline-secondary">2</button>
  </div>
  <div class="btn-group" role="group">
    <button class="btn btn-outline-secondary">3</button>
    <button class="btn btn-outline-secondary">4</button>
  </div>
</div>

<!-- vertical button group -->
<div class="btn-group-vertical" role="group">
  <button class="btn btn-outline-primary">Top</button>
  <button class="btn btn-outline-primary">Middle</button>
  <button class="btn btn-outline-primary">Bottom</button>
</div>

<!-- sizing -->
<div class="btn-group btn-group-lg">...</div>
<div class="btn-group btn-group-sm">...</div>

切换与复选框按钮

btn-check 是一个隐藏的复选框/单选按钮,与 btn-label 配对实现切换行为。输入框视觉隐藏;标签(样式化为按钮)显示状态。对于单个切换,使用复选框。对于互斥选项,使用同名单选按钮。按钮在选中时外观会改变。autocomplete='off' 防止浏览器状态恢复。这是制作按钮样式切换的可访问方式。

bootstrap
<!-- toggle button (single) -->
<input type="checkbox" class="btn-check" id="btn-check" autocomplete="off">
<label class="btn btn-primary" for="btn-check">Toggle</label>

<!-- checked by default -->
<input type="checkbox" class="btn-check" id="btn-check-checked" checked autocomplete="off">
<label class="btn btn-primary" for="btn-check-checked">Checked</label>

<!-- radio button group -->
<div class="btn-group" role="group" aria-label="Radio toggle">
  <input type="radio" class="btn-check" name="options" id="opt1" autocomplete="off" checked>
  <label class="btn btn-outline-primary" for="opt1">Option 1</label>
  <input type="radio" class="btn-check" name="options" id="opt2" autocomplete="off">
  <label class="btn btn-outline-primary" for="opt2">Option 2</label>
</div>

<!-- outline toggle (changes when checked) -->
<input type="checkbox" class="btn-check" id="btn-check-out" autocomplete="off">
<label class="btn btn-outline-success" for="btn-check-out">Toggle</label>

下拉按钮

下拉菜单需要切换按钮上的 data-bs-toggle='dropdown'。菜单是带 dropdown-item 链接的 ul.dropdown-menu。dropdown-divider 分隔组。分割按钮(dropdown-toggle-split)有独立的操作按钮和切换箭头——添加 visually-hidden 文本以确保可访问性。dropdown-item.active 标记当前选择;.disabled 使其变灰。下拉菜单需要 Bootstrap JS 包(包含 Popper 用于定位)。

bootstrap
<!-- button dropdown -->
<div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button"
          data-bs-toggle="dropdown" aria-expanded="false">
    Dropdown button
  </button>
  <ul class="dropdown-menu">
    <li><a class="dropdown-item" href="#">Action</a></li>
    <li><a class="dropdown-item" href="#">Another action</a></li>
    <li><hr class="dropdown-divider"></li>
    <li><a class="dropdown-item" href="#">Separated link</a></li>
  </ul>
</div>

<!-- split dropdown -->
<div class="btn-group">
  <button type="button" class="btn btn-primary">Primary</button>
  <button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split"
          data-bs-toggle="dropdown" aria-expanded="false">
    <span class="visually-hidden">Toggle Dropdown</span>
  </button>
  <ul class="dropdown-menu">...</ul>
</div>

<!-- dropdown with active/disabled items -->
<li><a class="dropdown-item active" href="#">Active</a></li>
<li><a class="dropdown-item disabled">Disabled</a></li>
08

卡片

基础卡片

卡片是灵活的容器,可选页眉、主体和页脚。card-img-top 在顶部放置图片。card-title、card-subtitle、card-text 样式化内容。宽度由父网格或 style 属性控制——卡片默认为全宽。card-header 和 card-footer 用于结构化内容。卡片用统一组件取代了 Bootstrap 3 的面板、井和缩略图。

bootstrap
<div class="card" style="width: 18rem;">
  <!-- optional image -->
  <img src="..." class="card-img-top" alt="...">

  <div class="card-body">
    <h5 class="card-title">Card title</h5>
    <h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6>
    <p class="card-text">Some quick example text to build on the card title.</p>
    <a href="#" class="btn btn-primary">Go somewhere</a>
  </div>
</div>

<!-- card sections -->
<div class="card">
  <div class="card-header">Header</div>
  <div class="card-body">Body content</div>
  <div class="card-footer text-muted">Footer</div>
</div>

卡片内容类型

卡片可以包含各种内容类型:图片、文本、列表组(使用 list-group-flush 移除边框并匹配卡片边缘)和链接(card-link 添加间距)。混合搭配部分——card-body、list-group、card-header、card-footer——构建你需要的确切卡片。list-group-flush 将列表无缝集成到卡片中,没有双边框。这种灵活性使卡片成为 Bootstrap 最通用的组件。

bootstrap
<!-- list group inside card -->
<div class="card" style="width: 18rem;">
  <div class="card-header">Featured</div>
  <ul class="list-group list-group-flush">
    <li class="list-group-item">Item 1</li>
    <li class="list-group-item">Item 2</li>
    <li class="list-group-item">Item 3</li>
  </ul>
  <div class="card-body">
    <a href="#" class="card-link">Card link</a>
    <a href="#" class="card-link">Another link</a>
  </div>
</div>

<!-- kitchen sink (all content types) -->
<div class="card">
  <img src="..." class="card-img-top">
  <div class="card-body">
    <h5 class="card-title">Title</h5>
    <p class="card-text">Text</p>
  </div>
  <ul class="list-group list-group-flush">
    <li class="list-group-item">List item</li>
  </ul>
  <div class="card-body">
    <a href="#" class="card-link">Link</a>
  </div>
</div>

卡片网格与组

card-group 连接卡片,共享边框和等高。对于响应式卡片网格,使用网格系统:row row-cols-1 row-cols-md-3 g-4 在移动端 1 列,桌面端 3 列,gap-4 间距。每张卡片放在 .col 中。网格方法比 card-group 更灵活——卡片可以有独立高度,你控制换行。仅在需要连接的等高卡片时使用 card-group。

bootstrap
<!-- card group (cards share border, equal height) -->
<div class="card-group">
  <div class="card">
    <img src="..." class="card-img-top">
    <div class="card-body">
      <h5 class="card-title">Card 1</h5>
    </div>
  </div>
  <div class="card">
    <div class="card-body">
      <h5 class="card-title">Card 2</h5>
    </div>
  </div>
  <div class="card">
    <div class="card-body">
      <h5 class="card-title">Card 3</h5>
    </div>
  </div>
</div>
<!-- cards have equal height, connected borders -->

<!-- using grid for responsive card layout -->
<div class="row row-cols-1 row-cols-md-3 g-4">
  <div class="col">
    <div class="card">...</div>
  </div>
  <div class="col">
    <div class="card">...</div>
  </div>
</div>

卡片导航

在 card-header 中添加 nav-tabs 或 nav-pills 实现卡片导航。card-header-tabs 和 card-header-pills 将导航与页眉边缘齐平集成。使用 nav-link active 标记当前标签,nav-link disabled 标记非活动。要使标签功能化(切换内容),添加 data-bs-toggle='tab' 和标签面板——Bootstrap 的 JS 处理切换。此模式常见于仪表板和带多视图的内容卡片。

bootstrap
<!-- card with nav tabs -->
<div class="card text-center">
  <div class="card-header">
    <ul class="nav nav-tabs card-header-tabs">
      <li class="nav-item">
        <a class="nav-link active" href="#">Active</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled">Disabled</a>
      </li>
    </ul>
  </div>
  <div class="card-body">
    <h5 class="card-title">Special title</h5>
    <p class="card-text">Content for active tab.</p>
    <a href="#" class="btn btn-primary">Go</a>
  </div>
</div>

<!-- card with pills -->
<div class="card-header">
  <ul class="nav nav-pills card-header-pills">
    <li class="nav-item"><a class="nav-link active" href="#">Active</a></li>
  </ul>
</div>

卡片变体与叠加

卡片颜色变体:bg-{color} 搭配 text-white/text-dark 用于实心背景;border-{color} 搭配 text-{color} 用于彩色边框。card-img-overlay 将文本放置在图片上(card-img 填充卡片,叠加内容在顶部)——使用 text-bg-dark 确保图片上的文本可读。text-center/text-start/text-end 控制文本对齐。对于深色图片叠加,确保文本和图片之间有足够的对比度。

bootstrap
<!-- colored card -->
<div class="card text-white bg-primary">
  <div class="card-header">Header</div>
  <div class="card-body">
    <h5 class="card-title">Primary card</h5>
    <p class="card-text">Text on colored background.</p>
  </div>
</div>

<!-- border colored card -->
<div class="card border-primary">
  <div class="card-header border-primary">Header</div>
  <div class="card-body text-primary">
    <h5 class="card-title">Primary border</h5>
  </div>
</div>

<!-- image overlay (text over image) -->
<div class="card text-bg-dark">
  <img src="..." class="card-img">
  <div class="card-img-overlay">
    <h5 class="card-title">Overlay title</h5>
    <p class="card-text">Text over the image.</p>
  </div>
</div>

<!-- text alignment -->
<div class="card text-center">Centered text</div>
<div class="card text-end">Right-aligned</div>
11

警告框

基础警告框

警告框显示上下文反馈消息。alert-{variant} 设置颜色(primary、success、danger、warning、info、light、dark)。role='alert' 用于屏幕阅读器可访问性。alert-link 样式化链接以匹配警告颜色。警告框用于:表单验证反馈、操作结果(已保存!已删除!)或重要通知。语义化选择颜色:success 表示积极,danger 表示错误,warning 表示警告,info 表示中性信息。

bootstrap
<!-- alert variants -->
<div class="alert alert-primary" role="alert">Primary alert</div>
<div class="alert alert-secondary" role="alert">Secondary alert</div>
<div class="alert alert-success" role="alert">Success! Well done.</div>
<div class="alert alert-danger" role="alert">Danger! Something went wrong.</div>
<div class="alert alert-warning" role="alert">Warning! Check this.</div>
<div class="alert alert-info" role="alert">Info! Note this.</div>
<div class="alert alert-light" role="alert">Light alert</div>
<div class="alert alert-dark" role="alert">Dark alert</div>

<!-- with link -->
<div class="alert alert-primary" role="alert">
  This is an alert with <a href="#" class="alert-link">a link</a>.
</div>

可关闭警告框

alert-dismissible 为关闭按钮添加内边距;带 data-bs-dismiss='alert' 的 btn-close 关闭它。fade show 启用淡出过渡。关闭后,警告框从 DOM 中移除(不只是隐藏)。通过 JS 创建 Alert 实例并调用 close()。closed.bs.alert 事件在移除后触发。如果要再次显示,必须重新创建 DOM 元素。对于持久关闭(不再显示),将状态存储在 localStorage 中。

bootstrap
<!-- dismissible alert -->
<div class="alert alert-warning alert-dismissible fade show" role="alert">
  <strong>Holy guacamole!</strong> You should check in on some of those fields.
  <button type="button" class="btn-close" data-bs-dismiss="alert"
          aria-label="Close"></button>
</div>

<!-- needs these classes:
     - alert-dismissible: adds padding for close button
     - fade show: enables transition

<!-- after dismissal, the alert is removed from DOM -->

<!-- via JavaScript -->
<script>
const alertEl = document.querySelector('.alert')
const alert = new bootstrap.Alert(alertEl)
alert.close()  // closes and removes
</script>

<!-- events -->
alertEl.addEventListener('closed.bs.alert', () => {
  console.log('alert was closed and removed')
})
</script>

带图标和内容的警告框

警告框可以包含丰富内容:标题(alert-heading)、段落、分隔线(hr)、图标和操作按钮。对于图标,使用 Bootstrap Icons(bi 类)或带 flex 对齐的 SVG。d-flex align-items-center 垂直居中图标和文本。在关闭按钮旁边包含操作按钮(如会话警告的'延长')。警告框不只是文本——它们是灵活的容器,用于重要的、可关闭的反馈。

bootstrap
<!-- alert with icon -->
<div class="alert alert-success d-flex align-items-center" role="alert">
  <svg class="bi flex-shrink-0 me-2" width="24" height="24">
    <use xlink:href="#check-circle-fill"/>
  </svg>
  <div>
    Operation completed successfully!
  </div>
</div>

<!-- alert with more content -->
<div class="alert alert-danger" role="alert">
  <h4 class="alert-heading">Error!</h4>
  <p>There was a problem processing your request.</p>
  <hr>
  <p class="mb-0">Please try again or contact support.</p>
</div>

<!-- alert with action button -->
<div class="alert alert-warning alert-dismissible" role="alert">
  Your session expires in 5 minutes.
  <button type="button" class="btn btn-warning btn-sm ms-3">
    Extend
  </button>
  <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>

Toast 通知

Toast 是轻量级通知(类似 Android toast)。它们在延迟后自动隐藏(默认 5 秒)。包装在 toast-container 中以堆叠。position-fixed 搭配 top-0 end-0 固定在右上角。aria-live='assertive' 向屏幕阅读器宣布。toast-header 有图标、标题、时间戳、关闭按钮;toast-body 有消息。与警告框不同,toast 不阻塞 UI——它们是非侵入性的。用于'已保存!'、'新消息'或后台任务完成。

bootstrap
<!-- toast container (top-right by default) -->
<div class="toast-container position-fixed top-0 end-0 p-3">
  <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
      <img src="..." class="rounded me-2" width="20">
      <strong class="me-auto">Bootstrap</strong>
      <small>11 mins ago</small>
      <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
    </div>
    <div class="toast-body">
      Hello, world! This is a toast message.
    </div>
  </div>
</div>

<script>
// show via JS
const toastEl = document.querySelector('.toast')
const toast = new bootstrap.Toast(toastEl, {
  delay: 5000,       // auto-hide after 5s
  autohide: true
})
toast.show()

// events
toastEl.addEventListener('shown.bs.toast', () => {
  console.log('toast visible')
})
</script>

实时警告区域

对于动态更新的警告框(状态消息、进度),使用 aria-live='polite'——屏幕阅读器在不打断的情况下宣布变化。aria-live='assertive' 立即宣布(用于严重错误)。aria-atomic='true' 在变化时读取整个内容(不只是变化部分)。role='alert' 隐式为 assertive。这种可访问性模式确保屏幕阅读器用户听到动态更新。与 alert 类结合获得视觉样式。

bootstrap
<!-- aria-live for dynamic alerts -->
<div class="alert alert-info" role="alert" aria-live="polite"
     aria-atomic="true" id="statusAlert">
  <!-- content updated dynamically -->
</div>

<script>
// update alert content
function showStatus(message, type = 'info') {
  const alert = document.getElementById('statusAlert')
  alert.className = 'alert alert-' + type
  alert.textContent = message
}

showStatus('Loading...', 'info')
// later:
showStatus('Data loaded!', 'success')

<!-- aria-live="polite" announces updates without interrupting -->
<!-- aria-live="assertive" interrupts immediately (urgent) -->

<!-- for form errors, use role="alert" (assertive by default) -->
<div role="alert" class="alert alert-danger" id="formError">
  Please fix the errors below.
</div>
</script>
12

徽章

基础徽章

徽章是小型计数/标签指示器。bg-{color} 设置背景;在浅色背景(warning、info、light)上添加 text-dark 以获得对比度。徽章相对于父元素的字体大小缩放——h1 徽章比 p 徽章大。徽章用于:未读计数、状态标签、'新'标签、版本号。它们是适合文本流的内联元素。

bootstrap
<!-- inline badges -->
<h1>Heading <span class="badge bg-secondary">New</span></h1>
<h2>Heading <span class="badge bg-secondary">New</span></h2>
<h3>Heading <span class="badge bg-secondary">New</span></h3>

<!-- colored badges -->
<span class="badge bg-primary">Primary</span>
<span class="badge bg-secondary">Secondary</span>
<span class="badge bg-success">Success</span>
<span class="badge bg-danger">Danger</span>
<span class="badge bg-warning text-dark">Warning</span>
<span class="badge bg-info text-dark">Info</span>
<span class="badge bg-light text-dark">Light</span>
<span class="badge bg-dark">Dark</span>

<!-- badge sizing scales with parent -->
<h1>Big <span class="badge bg-primary">Badge</span></h1>
<p>Small <span class="badge bg-primary">Badge</span></p>

胶囊徽章与圆角

rounded-pill 创建完全圆角的徽章(胶囊形状)。rounded-0 到 rounded-3 控制圆角比例。rounded-circle 搭配内边距创建圆形徽章——适用于通知计数。对于单位数字的完美圆形,设置相等的宽度和高度,并使用 d-flex align-items-center justify-content-center。胶囊徽章常用于标签和状态指示器。

bootstrap
<!-- pill badges (more rounded) -->
<span class="badge rounded-pill bg-primary">Primary</span>
<span class="badge rounded-pill bg-success">Success</span>
<span class="badge rounded-pill bg-danger">Danger</span>

<!-- rounded variations -->
<span class="badge rounded-0 bg-primary">Not rounded</span>
<span class="badge rounded-1 bg-primary">Slightly rounded</span>
<span class="badge rounded-2 bg-primary">Default rounded</span>
<span class="badge rounded-3 bg-primary">More rounded</span>
<span class="badge rounded-pill bg-primary">Full pill</span>

<!-- circle badge (fixed size, centered text) -->
<span class="badge rounded-circle bg-primary p-2">5</span>
<!-- needs width/height for perfect circle -->

按钮和导航中的徽章

按钮中的徽章:按钮上 position-relative,徽章上 position-absolute 搭配 top-0 start-100 translate-middle 将其放在右上角。徽章内的 visually-hidden 文本为屏幕阅读器提供上下文。导航链接和列表项中的徽章显示计数——使用 justify-content-between 将其推向右侧。'99+' 模式在计数超过显示限制时很常见。

bootstrap
<!-- badge inside button -->
<button type="button" class="btn btn-primary position-relative">
  Inbox
  <span class="position-absolute top-0 start-100 translate-middle
               badge rounded-pill bg-danger">
    99+
  </span>
</button>

<!-- badge with position outside button -->
<button class="btn btn-primary position-relative">
  Messages
  <span class="position-absolute top-0 start-100 translate-middle
               badge rounded-pill bg-danger">
    9
    <span class="visually-hidden">unread messages</span>
  </span>
</button>

<!-- badge in nav link -->
<ul class="nav nav-pills">
  <li class="nav-item">
    <a class="nav-link" href="#">
      Profile
      <span class="badge bg-secondary">3</span>
    </a>
  </li>
</ul>

<!-- badge in list item -->
<li class="list-group-item d-flex justify-content-between align-items-center">
  Messages
  <span class="badge bg-primary rounded-pill">14</span>
</li>

徽章指示器(点)

点徽章(无文本,仅彩色圆圈)表示状态而不显示计数——如'未读'或'在线'。使用 p-1 搭配 rounded-circle 获得小点,border-light 与背景分离。使用相同的 translate-middle 技术定位。在线状态点(绿色 = 在线,灰色 = 离线)位于头像的底角。徽章也可以包裹图标(Bootstrap Icons:bi bi-star-fill)和文本用于评分。

bootstrap
<!-- status dot badge -->
<button class="btn btn-primary position-relative">
  Notifications
  <span class="position-absolute top-0 start-100 translate-middle
               p-1 bg-danger border border-light rounded-circle">
    <span class="visually-hidden">New alerts</span>
  </span>
</button>

<!-- small dot (no text, just indicator) -->
<span class="position-absolute top-0 start-100 translate-middle
             p-1 bg-danger border border-light rounded-circle"></span>

<!-- online status indicator -->
<span class="position-relative d-inline-flex">
  <img src="avatar.jpg" class="rounded-circle" width="40">
  <span class="position-absolute bottom-0 end-0
               bg-success border border-light rounded-circle p-1">
  </span>
</span>
<!-- green dot = online -->

<!-- badge with icon -->
<span class="badge bg-primary">
  <i class="bi bi-star-fill"></i> 4.5
</span>

旋转器边框与增长

旋转器表示加载状态。spinner-border 是旋转的环;spinner-grow 是脉动的圆圈。text-* 为其着色。spinner-border-sm/grow-sm 更小。通过宽/高 CSS 自定义尺寸。始终包含 role='status' 和 visually-hidden 文本以确保可访问性。在按钮中,使用 spinner-border-sm 搭配 disabled 显示加载操作。旋转器仅使用 CSS(无 JS)——通过边框和不透明度过渡动画。

bootstrap
<!-- border spinner (rotating border) -->
<div class="spinner-border" role="status">
  <span class="visually-hidden">Loading...</span>
</div>

<!-- colored spinner -->
<div class="spinner-border text-primary"></div>
<div class="spinner-border text-success"></div>
<div class="spinner-border text-danger"></div>

<!-- grow spinner (pulsating circle) -->
<div class="spinner-grow" role="status">
  <span class="visually-hidden">Loading...</span>
</div>

<!-- sizes -->
<div class="spinner-border spinner-border-sm">Small</div>
<div class="spinner-grow spinner-grow-sm">Small grow</div>

<!-- custom size via CSS -->
<div class="spinner-border" style="width: 3rem; height: 3rem;"></div>

<!-- spinner in button -->
<button class="btn btn-primary" disabled>
  <span class="spinner-border spinner-border-sm"></span>
  Loading...
</button>

<!-- spinner with text -->
<div class="d-flex align-items-center">
  <strong>Loading...</strong>
  <div class="spinner-border ms-auto"></div>
</div>
13

进度条与旋转器

基础进度条

进度条显示任务完成情况。通过内联样式将宽度设置为百分比。role='progressbar' 搭配 aria-valuenow/min/max 用于可访问性。高度设置在 .progress 容器上(默认 1rem)。栏上的 bg-{color} 改变其颜色。栏内的标签文本是可选的——极简栏可省略。始终通过 style(非 class)设置宽度,因为值是动态的。

bootstrap
<!-- basic progress bar -->
<div class="progress">
  <div class="progress-bar" role="progressbar" style="width: 50%"
       aria-valuenow="50" aria-valuemin="0" aria-valuemax="100">
    50%
  </div>
</div>

<!-- without label -->
<div class="progress">
  <div class="progress-bar" style="width: 75%" role="progressbar"
       aria-valuenow="75" aria-valuemin="0" aria-valuemax="100"></div>
</div>

<!-- height (set on container) -->
<div class="progress" style="height: 1px;">
  <div class="progress-bar" style="width: 25%"></div>
</div>
<div class="progress" style="height: 20px;">
  <div class="progress-bar" style="width: 25%"></div>
</div>

<!-- background -->
<div class="progress">
  <div class="progress-bar bg-success" style="width: 25%">25%</div>
</div>

条纹与动画进度条

progress-bar-striped 添加对角条纹。progress-bar-animated 使条纹移动(用于活动/进行中任务)。仅为当前运行的任务使用动画——完成时使用静态栏。通过 JS 更改进度,更改 style.width 和 aria-valuenow。动画使用 CSS——移动无需 JS。将 bg-* 与 striped 组合获得彩色条纹栏。

bootstrap
<!-- striped progress bar -->
<div class="progress">
  <div class="progress-bar progress-bar-striped" style="width: 50%">
    50%
  </div>
</div>

<!-- animated stripes (for in-progress tasks) -->
<div class="progress">
  <div class="progress-bar progress-bar-striped progress-bar-animated"
       style="width: 75%" role="progressbar">
    75%
  </div>
</div>

<!-- colored striped -->
<div class="progress">
  <div class="progress-bar progress-bar-striped bg-success" style="width: 100%">
    Complete
  </div>
</div>

<!-- update via JS -->
<div class="progress">
  <div class="progress-bar" id="myBar" style="width: 0%"></div>
</div>
<script>
const bar = document.getElementById('myBar')
bar.style.width = '60%'  // update progress
bar.setAttribute('aria-valuenow', '60')
</script>

多个进度条

一个 .progress 容器内的多个 progress-bar div 并排堆叠——每个占总宽度的百分比。这对于显示组合很有用(如存储:25% 照片,30% 视频,20% 应用)。栏共享相同高度且相邻无间隙。总数理想情况下应总和为 100%(或更少表示未完成)。每个可以有独立的颜色和标签。

bootstrap
<!-- stacked bars in one container -->
<div class="progress">
  <div class="progress-bar" style="width: 15%">15%</div>
  <div class="progress-bar bg-success" style="width: 30%">30%</div>
  <div class="progress-bar bg-info" style="width: 20%">20%</div>
</div>
<!-- total: 65% filled, 35% empty -->

<!-- stacked with different colors -->
<div class="progress" style="height: 30px;">
  <div class="progress-bar bg-danger" style="width: 25%">Errors</div>
  <div class="progress-bar bg-warning" style="width: 25%">Warnings</div>
  <div class="progress-bar bg-success" style="width: 50%">Success</div>
</div>

<!-- each bar takes its percentage of the full width -->
<!-- they sit side by side, not overlapping -->

占位符加载

占位符(骨架加载)显示内容将出现的灰色块——对于内容密集的页面比旋转器更好。placeholder-glow 创建脉动闪光;placeholder-wave 创建移动波浪。col-* 设置每个块的宽度。对于骨架卡片,在卡片组件内使用 placeholder 搭配 aria-hidden='true'。这在数据加载前为用户提供布局预览,减少感知等待时间。

bootstrap
<!-- placeholder (gray animated blocks) -->
<div class="placeholder-glow">
  <span class="placeholder col-12"></span>
  <span class="placeholder col-12"></span>
  <span class="placeholder col-8"></span>
</div>

<!-- wave animation -->
<div class="placeholder-wave">
  <span class="placeholder col-12"></span>
</div>

<!-- placeholder card (skeleton loading) -->
<div class="card" aria-hidden="true">
  <div class="card-body">
    <h5 class="card-title placeholder-glow">
      <span class="placeholder col-6"></span>
    </h5>
    <p class="card-text placeholder-glow">
      <span class="placeholder col-7"></span>
      <span class="placeholder col-4"></span>
      <span class="placeholder col-4"></span>
      <span class="placeholder col-6"></span>
    </p>
    <a class="btn btn-primary disabled placeholder col-6"></a>
  </div>
</div>

范围滑块

form-range 样式化原生范围输入(滑块)。设置 min、max 和 step 属性用于范围和增量。滑块默认为全宽。对于值显示,使用 oninput 在用户拖动时更新标签。disabled 使其变灰。范围输入适用于音量、不透明度或任何不需要精确的连续值。始终与标签配对以确保可访问性。

bootstrap
<!-- range input -->
<label for="customRange1" class="form-label">Example range</label>
<input type="range" class="form-range" id="customRange1" min="0" max="5" step="0.5">

<!-- with value display -->
<div class="d-flex">
  <input type="range" class="form-range me-2" id="range"
         min="0" max="100" oninput="document.getElementById('val').textContent = this.value">
  <span id="val" class="badge bg-primary">50</span>
</div>

<!-- disabled -->
<input type="range" class="form-range" disabled>

<!-- min, max, step -->
<input type="range" class="form-range" min="-10" max="10" step="2" value="0">
14

工具类

间距(外边距与内边距)

间距工具类遵循 {属性}{边}-{尺寸} 格式。m = 外边距,p = 内边距。边:t/b(上/下),s/e(起始/结束——LTR 中为左/右),x(左+右),y(上+下),空白(全部)。尺寸 0-5 映射到间距比例(0、0.25rem、0.5rem、1rem、1.5rem、3rem)。mx-auto 居中块元素。响应式:添加断点(mt-md-3)。Bootstrap 5 将 left/right 重命名为 start/end 以支持 RTL。

bootstrap
<!-- format: {property}{sides}-{size} -->
<!-- property: m (margin), p (padding) -->
<!-- sides: t (top), b (bottom), s (start/left), e (end/right), x (both), y (both), blank (all) -->
<!-- size: 0, 1, 2, 3, 4, 5, auto -->

<div class="mt-3">margin-top: 1rem</div>
<div class="mb-4">margin-bottom: 1.5rem</div>
<div class="ms-2">margin-left: 0.5rem (start)</div>
<div class="me-2">margin-right: 0.5rem (end)</div>
<div class="mx-auto">margin: 0 auto (centered)</div>
<div class="my-5">margin top+bottom: 3rem</div>

<div class="p-3">padding: 1rem (all sides)</div>
<div class="px-4">padding left+right: 1.5rem</div>
<div class="pt-2">padding-top: 0.5rem</div>

<!-- responsive: {property}{sides}-{breakpoint}-{size} -->
<div class="mt-0 mt-md-3">No margin on mobile, 1rem on md+</div>
<div class="p-2 p-lg-4">Small padding, larger on lg+</div>

颜色与背景

text-{color} 设置文本颜色;bg-{color} 设置背景。text-bg-{color}(Bootstrap 5.2+)自动为背景设置对比文本颜色。bg-gradient 添加微妙渐变。不透明度:text-opacity-50 或 bg-opacity-50(10%、25%、50%、75%、100%)。text-muted 是灰色(次要文本)。始终确保文本和背景之间有足够对比度——在深色背景上使用 text-white。颜色承载语义含义(success=绿色,danger=红色)。

bootstrap
<!-- text colors -->
<p class="text-primary">Primary text</p>
<p class="text-success">Success text</p>
<p class="text-danger">Danger text</p>
<p class="text-muted">Muted text</p>
<p class="text-white bg-dark">White on dark</p>

<!-- background colors -->
<div class="bg-primary text-white">Primary bg</div>
<div class="bg-success text-white">Success bg</div>
<div class="bg-light">Light bg</div>
<div class="bg-dark text-white">Dark bg</div>

<!-- gradient background -->
<div class="bg-primary bg-gradient text-white p-3">
  Gradient background
</div>

<!-- opacity -->
<div class="text-primary text-opacity-50">50% opacity text</div>
<div class="bg-primary bg-opacity-50">50% opacity bg</div>

<!-- text color with background theme -->
<div class="text-bg-primary">Primary (auto text color)</div>

显示与 Flexbox

d-* 设置 display 属性(d-none 隐藏元素)。响应式 d-{breakpoint}-* 在断点处改变显示——d-none d-md-block 在移动端隐藏,桌面端显示。d-flex 启用 flexbox;flex-direction、justify-content-*、align-items-* 和 flex-wrap 控制 flex 布局。这些工具类取代了大多数布局的自定义 CSS。d-md-flex 仅在 md+ 激活 flex。无需媒体查询即可组合实现复杂的响应式布局。

bootstrap
<!-- display utilities -->
<div class="d-none">display: none</div>
<div class="d-inline">display: inline</div>
<div class="d-inline-block">display: inline-block</div>
<div class="d-block">display: block</div>
<div class="d-flex">display: flex</div>
<div class="d-inline-flex">display: inline-flex</div>

<!-- responsive display -->
<div class="d-none d-md-block">Hidden on mobile, block on md+</div>
<div class="d-block d-md-none">Visible only below md</div>

<!-- flex direction -->
<div class="d-flex flex-column">Column</div>
<div class="d-flex flex-row-reverse">Reversed row</div>

<!-- justify content -->
<div class="d-flex justify-content-center">Center</div>
<div class="d-flex justify-content-between">Space between</div>
<div class="d-flex justify-content-around">Space around</div>

<!-- align items -->
<div class="d-flex align-items-center">Vertically centered</div>
<div class="d-flex align-items-end">Bottom aligned</div>

<!-- flex wrap -->
<div class="d-flex flex-wrap">Wrap</div>
<div class="d-flex flex-nowrap">No wrap</div>

定位与浮动

position-* 设置 CSS 定位。position-sticky 搭配 top-0 创建粘性页眉(滚动到时固定)。top/bottom/start/end(0 或 50%)设置偏移。translate-middle 居中元素(组合 top-50 start-50 实现完美居中)。浮动(float-start/end)是遗留方式——布局使用 flexbox。clearfix 清除浮动子元素。fixed-top/fixed-bottom 将元素固定到视口。导航栏首选 sticky 而非 fixed,因为它初始不重叠内容。

bootstrap
<!-- position -->
<div class="position-static">Static (default)</div>
<div class="position-relative">Relative (offset parent)</div>
<div class="position-absolute">Absolute</div>
<div class="position-fixed">Fixed (viewport)</div>
<div class="position-sticky top-0">Sticky (sticks at top)</div>

<!-- positioning with insets -->
<div class="position-absolute top-0 start-0">Top-left</div>
<div class="position-absolute top-0 end-0">Top-right</div>
<div class="position-absolute bottom-0 start-50">Bottom-center</div>

<!-- center with translate -->
<div class="position-absolute top-50 start-50 translate-middle">
  Perfectly centered
</div>

<!-- floats (use flexbox instead when possible) -->
<div class="float-start">Float left</div>
<div class="float-end">Float right</div>
<div class="clearfix">Clear floats</div>

<!-- fixed top/bottom -->
<div class="fixed-top">Pinned to top</div>
<div class="fixed-bottom">Pinned to bottom</div>

边框、阴影与圆角

border 在特定边添加/移除边框。border-{color} 为其着色;border-{1-5} 设置宽度。rounded-* 控制圆角:rounded-0(无)、rounded(默认)、rounded-3(更大)、rounded-pill(胶囊)、rounded-circle(50%)。rounded-{side} 仅圆角特定角。shadow-* 添加盒阴影:none、sm、默认、lg。阴影添加深度——shadow-sm 用于微妙提升,shadow-lg 用于模态框/浮动元素。这些工具类无需自定义 CSS 即可处理大多数视觉样式。

bootstrap
<!-- borders -->
<div class="border">All borders</div>
<div class="border-top">Top only</div>
<div class="border border-0">No borders</div>
<div class="border-top-0">Remove top</div>

<!-- border color -->
<div class="border border-primary">Primary border</div>
<div class="border border-danger">Danger border</div>

<!-- border width -->
<div class="border border-2">2px border</div>
<div class="border border-4">4px border</div>

<!-- border radius -->
<div class="rounded">Default radius</div>
<div class="rounded-0">No radius</div>
<div class="rounded-3">Larger radius</div>
<div class="rounded-pill">Pill shape</div>
<div class="rounded-circle">Circle</div>
<div class="rounded-top">Top corners only</div>

<!-- shadows -->
<div class="shadow-none">No shadow</div>
<div class="shadow-sm">Small shadow</div>
<div class="shadow">Regular shadow</div>
<div class="shadow-lg">Large shadow</div>
15

图片与图形

响应式图片

img-fluid 使图片响应式(max-width: 100%,height: auto)——它们不会溢出容器。w-100 强制全宽。figure/figure-img/figure-caption 提供语义化的带标题图片(比 div + p 更好)。float-start/end 对齐图片;mx-auto d-block 居中。rounded 添加圆角。始终包含 alt 文本以确保可访问性——为屏幕阅读器描述图片。对于装饰性图片,使用 alt=''。

bootstrap
<!-- responsive image (scales with parent) -->
<img src="photo.jpg" class="img-fluid" alt="Responsive image">
<!-- max-width: 100%; height: auto; -->

<!-- full-width image -->
<img src="banner.jpg" class="img-fluid w-100" alt="Banner">

<!-- image with figure -->
<figure class="figure">
  <img src="photo.jpg" class="figure-img img-fluid rounded" alt="...">
  <figcaption class="figure-caption text-end">
    A caption for the image.
  </figcaption>
</figure>

<!-- image alignment -->
<img src="..." class="rounded float-start" alt="Left">
<img src="..." class="rounded float-end" alt="Right">
<img src="..." class="rounded mx-auto d-block" alt="Centered">

<!-- center with text-center on parent -->
<div class="text-center">
  <img src="..." class="rounded" alt="Centered">
</div>

图片形状与缩略图

图片形状:rounded(圆角)、rounded-circle(圆形——在方形图片上效果最佳)、rounded-pill(胶囊)。img-thumbnail 添加边框、内边距和圆角——呈现照片打印外观。将 img-thumbnail 与 rounded-circle 组合获得圆形缩略图。对于头像,设置明确的宽度和高度以预留空间并防止布局偏移。形状类适用于任何元素,不仅图片——适用于视频缩略图或个人资料图片。

bootstrap
<!-- rounded corners -->
<img src="..." class="rounded" alt="Rounded">

<!-- fully rounded (circle) -->
<img src="..." class="rounded-circle" alt="Circle">

<!-- thumbnail (border + padding) -->
<img src="..." class="img-thumbnail" alt="Thumbnail">
<!-- adds padding, border, rounded corners -->

<!-- pill shape -->
<img src="..." class="rounded-pill" alt="Pill">

<!-- combination: thumbnail + circle -->
<img src="..." class="img-thumbnail rounded-circle" alt="Circle thumb">

<!-- avatar sizes (set width/height) -->
<img src="avatar.jpg" class="rounded-circle" width="40" height="40" alt="Avatar">
<img src="avatar.jpg" class="rounded-circle" width="100" height="100" alt="Large avatar">

图形与标题

figure 是带标题图片的语义 HTML 元素——比 div 更好地支持可访问性。figure-img 样式化图片(与 img-fluid 和 rounded 组合)。figure-caption 样式化标题文本(默认为静音色)。text-start/center/end 对齐标题。将图片包装在 <a> 中以实现可点击放大。figures 是编辑内容、文档和图库的正确语义选择。

bootstrap
<!-- figure with caption -->
<figure class="figure">
  <img src="photo.jpg" class="figure-img img-fluid rounded" alt="Photo">
  <figcaption class="figure-caption">
    Caption describing the image.
  </figcaption>
</figure>

<!-- right-aligned caption -->
<figure class="figure">
  <img src="photo.jpg" class="figure-img img-fluid rounded" alt="Photo">
  <figcaption class="figure-caption text-end">
    Right-aligned caption.
  </figcaption>
</figure>

<!-- centered caption -->
<figcaption class="figure-caption text-center">Centered</figcaption>

<!-- figure with link -->
<figure class="figure">
  <a href="full-size.jpg">
    <img src="thumb.jpg" class="figure-img img-fluid rounded" alt="Click to enlarge">
  </a>
  <figcaption class="figure-caption">Click to view full size</figcaption>
</figure>

背景图片

Bootstrap 没有 background-image 工具类(图片依赖内容),所以使用内联样式。background-size: cover 填充容器而不失真;background-position: center 聚焦中心。对于图片上的文本,添加渐变叠加(底部深色)以确保可读性。包装器上 position-relative 搭配 position-absolute 层可以堆叠图片、叠加和文本。这是英雄区域和图片卡片的模式。

bootstrap
<!-- background image via inline style -->
<div style="background-image: url('bg.jpg');
            background-size: cover;
            background-position: center;
            height: 400px;">
  <div class="d-flex align-items-center justify-content-center h-100">
    <h1 class="text-white">Hero text over image</h1>
  </div>
</div>

<!-- parallax-like fixed background -->
<div style="background-image: url('bg.jpg');
            background-attachment: fixed;
            background-size: cover;
            height: 300px;">
</div>

<!-- gradient overlay for text readability -->
<div class="position-relative">
  <img src="bg.jpg" class="img-fluid" alt="">
  <div class="position-absolute top-0 start-0 w-100 h-100"
       style="background: linear-gradient(to bottom, transparent, rgba(0,0,0,0.7));">
  </div>
  <div class="position-absolute bottom-0 start-0 p-4 text-white">
    <h2>Text over gradient</h2>
  </div>
</div>

图片网格与画廊

图片网格使用标准 row/col 系统,g-* 用于间距。对于无论纵横比如何都要等高的图片,设置固定高度容器并在 img 上使用 object-fit: cover 搭配 w-100 h-100。row-cols-* 创建等宽列而无需在每个项目上指定 col-*。对于真正的瀑布流(可变高度,无间隙),需要 CSS columns 或 JavaScript 库——Bootstrap 的网格原生不支持瀑布流。img-fluid 确保图片不会溢出其网格单元。

bootstrap
<!-- responsive image grid -->
<div class="row g-2">
  <div class="col-6 col-md-4">
    <img src="1.jpg" class="img-fluid rounded" alt="">
  </div>
  <div class="col-6 col-md-4">
    <img src="2.jpg" class="img-fluid rounded" alt="">
  </div>
  <div class="col-6 col-md-4">
    <img src="3.jpg" class="img-fluid rounded" alt="">
  </div>
  <div class="col-6 col-md-4">
    <img src="4.jpg" class="img-fluid rounded" alt="">
  </div>
</div>

<!-- equal-height images with object-fit -->
<div class="row g-3">
  <div class="col-md-4">
    <div style="height: 200px;">
      <img src="tall.jpg" class="w-100 h-100"
           style="object-fit: cover;" alt="">
    </div>
  </div>
</div>

<!-- masonry-like with columns -->
<div class="row row-cols-1 row-cols-md-3 g-3">
  <div class="col"><img src="1.jpg" class="img-fluid rounded"></div>
  <div class="col"><img src="2.jpg" class="img-fluid rounded"></div>
</div>
17

折叠与手风琴

基础折叠

折叠通过高度动画切换元素可见性。触发器:data-bs-toggle='collapse' 搭配 data-bs-target(按钮)或 href(锚点)指向可折叠元素的 id。.collapse 隐藏;.collapse.show 可见。触发器上的 aria-expanded 反映状态;aria-controls 链接触发器和目标。操作使用按钮,导航使用锚点。动画平滑地从 0 过渡高度到 auto。

bootstrap
<!-- collapse trigger (button) -->
<p>
  <button class="btn btn-primary" type="button"
          data-bs-toggle="collapse" data-bs-target="#collapseExample"
          aria-expanded="false" aria-controls="collapseExample">
    Toggle collapse
  </button>
</p>
<div class="collapse" id="collapseExample">
  <div class="card card-body">
    This content is hidden by default and shown when the button is clicked.
  </div>
</div>

<!-- collapse via anchor -->
<a class="btn btn-primary" data-bs-toggle="collapse"
   href="#collapseExample2" role="button" aria-expanded="false"
   aria-controls="collapseExample2">
  Link trigger
</a>
<div class="collapse" id="collapseExample2">
  <div class="card card-body">Content</div>
</div>

<!-- shown by default -->
<div class="collapse show" id="alwaysShown">
  <div class="card card-body">Shown initially</div>
</div>

手风琴

手风琴是一组折叠,其中 data-bs-parent 确保同时只打开一个(打开一个关闭其他)。结构:accordion > accordion-item > accordion-header(带 accordion-button)+ accordion-collapse(带 accordion-body)。第一项可以有 'show' 类以默认展开。按钮上的 'collapsed' 类表示折叠状态(旋转箭头)。aria-expanded 和 aria-controls 对可访问性必不可少。parent 属性创建独占打开行为。

bootstrap
<div class="accordion" id="accordionExample">
  <div class="accordion-item">
    <h2 class="accordion-header" id="headingOne">
      <button class="accordion-button" type="button"
              data-bs-toggle="collapse" data-bs-target="#collapseOne"
              aria-expanded="true" aria-controls="collapseOne">
        Accordion Item #1
      </button>
    </h2>
    <div id="collapseOne" class="accordion-collapse collapse show"
         aria-labelledby="headingOne" data-bs-parent="#accordionExample">
      <div class="accordion-body">
        <strong>First item content.</strong> Shown by default.
      </div>
    </div>
  </div>

  <div class="accordion-item">
    <h2 class="accordion-header" id="headingTwo">
      <button class="accordion-button collapsed" type="button"
              data-bs-toggle="collapse" data-bs-target="#collapseTwo"
              aria-expanded="false" aria-controls="collapseTwo">
        Accordion Item #2
      </button>
    </h2>
    <div id="collapseTwo" class="accordion-collapse collapse"
         aria-labelledby="headingTwo" data-bs-parent="#accordionExample">
      <div class="accordion-body">
        <strong>Second item content.</strong>
      </div>
    </div>
  </div>
</div>

手风琴 Flush 与变体

accordion-flush 移除外边框和背景——用于集成到卡片或容器中而没有双边框。折叠项上没有 data-bs-parent 时,多个部分可以同时保持打开(始终打开模式)。有 data-bs-parent 时,打开一个关闭其他(标准手风琴)。根据 UX 选择:FAQ 使用独占(一个打开),用户一次阅读一个;导航或设置使用多开,用户可能比较部分。

bootstrap
<!-- flush (no borders, no background) -->
<div class="accordion accordion-flush" id="accordionFlush">
  <div class="accordion-item">
    <h2 class="accordion-header">
      <button class="accordion-button collapsed" data-bs-toggle="collapse"
              data-bs-target="#flush1">
        Item #1
      </button>
    </h2>
    <div id="flush1" class="accordion-collapse collapse">
      <div class="accordion-body">Flush content</div>
    </div>
  </div>
</div>
<!-- flush removes outer borders and background -->

<!-- always-open (no exclusive behavior) -->
<div class="accordion" id="accordionAlwaysOpen">
  <div class="accordion-item">
    <h2 class="accordion-header">
      <button class="accordion-button" data-bs-toggle="collapse"
              data-bs-target="#open1">
        Item #1
      </button>
    </h2>
    <div id="open1" class="accordion-collapse collapse show">
      <!-- no data-bs-parent = stays open when others open -->
      <div class="accordion-body">Content</div>
    </div>
  </div>
</div>

通过 JavaScript 控制折叠

通过 JS 控制折叠:new bootstrap.Collapse(el, options)。toggle: false 防止初始化时自动切换。parent: 选择器创建手风琴行为(关闭兄弟元素)。方法:show()、hide()、toggle()、dispose()。事件:show/shown/hide/hidden.bs.collapse——使用 shown/hidden(过去时)进行动画后操作,如聚焦输入框或更新 aria。适用于编程控制,如基于 URL 哈希或表单状态展开部分。

bootstrap
<div class="collapse" id="jsCollapse">
  <div class="card card-body">Content</div>
</div>

<script>
const collapseEl = document.getElementById('jsCollapse')
const collapse = new bootstrap.Collapse(collapseEl, {
  toggle: false,      // don't toggle on init
  parent: null        // or selector for accordion behavior
})

// methods
collapse.show()
collapse.hide()
collapse.toggle()

// dispose (removes instance)
collapse.dispose()

// events
collapseEl.addEventListener('show.bs.collapse', () => {
  console.log('about to show')
})
collapseEl.addEventListener('shown.bs.collapse', () => {
  console.log('fully shown')
})
collapseEl.addEventListener('hide.bs.collapse', () => {
  console.log('about to hide')
})
collapseEl.addEventListener('hidden.bs.collapse', () => {
  console.log('fully hidden')
})
</script>

多目标折叠

data-bs-target 接受 CSS 选择器,因此一个触发器可以切换多个元素——使用共享类(.multi-collapse)全部定位。反过来,多个触发器可以控制同一目标(每个都有 data-bs-target='#shared')。这适用于控制多个部分的'全部显示'/'全部隐藏'按钮,或响应式布局中不同位置的不同按钮控制同一面板。选择器方法非常灵活。

bootstrap
<!-- one trigger toggles multiple targets -->
<p>
  <button class="btn btn-primary" data-bs-toggle="collapse"
          data-bs-target=".multi-collapse" aria-expanded="false">
    Toggle both
  </button>
</p>

<div class="row">
  <div class="col">
    <div class="collapse multi-collapse" id="first">
      <div class="card card-body">First block</div>
    </div>
  </div>
  <div class="col">
    <div class="collapse multi-collapse" id="second">
      <div class="card card-body">Second block</div>
    </div>
  </div>
</div>

<!-- multiple triggers control one target -->
<button class="btn btn-primary" data-bs-toggle="collapse"
        data-bs-target="#shared">Show A</button>
<button class="btn btn-secondary" data-bs-toggle="collapse"
        data-bs-target="#shared">Show B</button>
<div class="collapse" id="shared">
  <div class="card card-body">Shared content</div>
</div>
19

图标与无障碍

Bootstrap 图标

Bootstrap Icons 是独立的图标库(不包含在 CSS 中)。引入 CSS,然后使用 <i class='bi bi-{name}'></i>。使用 fs-*(字体大小)工具类调整图标大小。使用 text-* 类为其着色。按钮中的图标通过视觉提示改善用户体验。仅图标按钮必须有 aria-label 以确保屏幕阅读器可访问——没有它,按钮没有可访问名称。在 icons.getbootstrap.com 浏览图标。图标是 SVG 字体,所以在任何尺寸下都清晰缩放。

bootstrap
<!-- Bootstrap Icons (separate from CSS framework) -->
<link rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">

<!-- usage: <i class="bi bi-{name}"></i> -->
<i class="bi bi-alarm"></i>
<i class="bi bi-arrow-right"></i>
<i class="bi bi-check-circle"></i>
<i class="bi bi-github"></i>

<!-- sizing with utility classes -->
<i class="bi bi-star fs-1"></i>  <!-- font-size 1 -->
<i class="bi bi-star fs-3"></i>
<i class="bi bi-star fs-6"></i>

<!-- colored icons -->
<i class="bi bi-exclamation-triangle text-warning fs-3"></i>
<i class="bi bi-check-circle text-success fs-3"></i>

<!-- icon in a button -->
<button class="btn btn-primary">
  <i class="bi bi-download"></i> Download
</button>

<!-- icon-only button (needs aria-label) -->
<button class="btn btn-link" aria-label="Search">
  <i class="bi bi-search"></i>
</button>

无障碍:ARIA 与角色

Bootstrap 组件包含 ARIA 属性,但自定义控件必须自行添加。aria-label 为仅图标按钮提供名称。aria-labelledby 引用另一个元素的 id 作为标签。aria-describedby 指向帮助文本。aria-expanded 反映切换状态(true/false)。aria-current='page' 标记当前导航项。使用语义 HTML(nav、main、aside、header、footer),它们具有隐式 ARIA 角色——比在 div 上添加 role 属性更好。

bootstrap
<!-- landmark roles (use semantic HTML) -->
<nav role="navigation">...</nav>
<main role="main">...</main>
<aside role="complementary">...</aside>
<footer role="contentinfo">...</footer>

<!-- aria-label for unlabeled controls -->
<button aria-label="Close" class="btn-close"></button>
<button aria-label="Search" class="btn"><i class="bi bi-search"></i></button>

<!-- aria-labelledby (reference another element) -->
<div role="dialog" aria-labelledby="modalTitle">
  <h2 id="modalTitle">Modal Heading</h2>
</div>

<!-- aria-describedby (descriptive text) -->
<input aria-describedby="emailHelp" id="email">
<small id="emailHelp">We'll never share your email.</small>

<!-- aria-expanded for toggles -->
<button aria-expanded="false" data-bs-toggle="collapse">
  Toggle
</button>

<!-- aria-current for current page -->
<a aria-current="page" class="nav-link active">Home</a>

视觉隐藏与屏幕阅读器

visually-hidden 视觉隐藏内容但保留给屏幕阅读器——用于仅图标按钮的标签或额外上下文。visually-hidden-focusable 隐藏直到键盘聚焦(非常适合 Tab 时出现的'跳到主要内容'链接)。aria-hidden='true' 做相反的事:可见但不宣布(用于装饰性元素)。始终将跳过链接作为第一个可聚焦元素以确保键盘可访问性。这些对于 WCAG 合规至关重要。

bootstrap
<!-- visually hidden (hidden visually, read by screen readers) -->
<span class="visually-hidden">This text is read by screen readers</span>

<!-- for icon-only buttons -->
<button class="btn btn-primary" aria-label="Search">
  <i class="bi bi-search"></i>
  <span class="visually-hidden">Search</span>
</button>

<!-- skip link (keyboard users skip to content) -->
<a href="#main-content" class="visually-hidden-focusable">
  Skip to main content
</a>

<!-- visually-hidden-focusable: hidden until focused -->
<!-- useful for skip links that appear on Tab -->

<!-- main content target -->
<main id="main-content">
  <!-- skip link jumps here -->
</main>

<!-- hide from screen readers only (still visible) -->
<div aria-hidden="true">
  Decorative content (not announced)
</div>

减少动画与深色模式

深色模式:在 <html> 上设置 data-bs-theme='dark'——Bootstrap 交换 CSS 变量。通过 JS 更改属性切换。使用 matchMedia('(prefers-color-scheme: dark)') 尊重系统偏好。对于减少动画,当用户设置了 prefers-reduced-motion: reduce 时,Bootstrap 自动禁用大多数动画。你可以添加更多规则进一步减少动画。将用户的主题偏好存储在 localStorage 中。这些功能使你的站点对所有用户都可访问和舒适。

bootstrap
<!-- dark mode via data attribute -->
<html data-bs-theme="dark">
  <!-- entire page in dark mode -->
</html>

<!-- toggle dark mode via JS -->
<button id="themeToggle">Toggle theme</button>
<script>
const html = document.documentElement
const current = html.getAttribute('data-bs-theme')
html.setAttribute('data-bs-theme', current === 'dark' ? 'light' : 'dark')
</script>

<!-- respect system preference -->
<script>
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  document.documentElement.setAttribute('data-bs-theme', 'dark')
}
</script>

<!-- reduced motion: Bootstrap respects this automatically -->
@media (prefers-reduced-motion: reduce) {
  /* Bootstrap disables transitions and animations */
  /* but you can add more */
  .carousel {
    transition: none;
  }
}

焦点管理与键盘

永远不要移除焦点轮廓(outline: none)而不提供替代——键盘用户需要它们。Bootstrap 的 focus-visible 仅在键盘聚焦时显示环,鼠标不显示。对于模态框,显示时将焦点移入模态框,隐藏时返回触发器。自定义小部件(标签页、菜单)需要箭头键导航——实现 Arrow 键、Enter、Space 和 Escape 的 keydown 处理程序。正确的 tabindex 管理(0 表示可聚焦,-1 表示可编程聚焦)确保逻辑的 Tab 顺序。这对仅键盘用户至关重要。

bootstrap
<!-- visible focus (don't remove outlines!) -->
<!-- Bootstrap provides focus-visible styling -->
<button class="btn btn-primary">Has visible focus ring</button>

<!-- skip link (first focusable element) -->
<body>
  <a href="#main" class="visually-hidden-focusable">Skip to content</a>
  <nav>...</nav>
  <main id="main">...</main>
</body>

<!-- focus management for modals -->
<script>
const modal = document.getElementById('myModal')
modal.addEventListener('shown.bs.modal', () => {
  // focus first input in modal
  modal.querySelector('input')?.focus()
})
modal.addEventListener('hidden.bs.modal', () => {
  // return focus to trigger
  document.getElementById('openModalBtn').focus()
})
</script>

<!-- keyboard navigation for custom widgets -->
<div role="tablist">
  <button role="tab" tabindex="0">Tab 1</button>
  <button role="tab" tabindex="-1">Tab 2</button>
</div>
<script>
// arrow key navigation
document.querySelectorAll('[role="tab"]').forEach((tab, i, tabs) => {
  tab.addEventListener('keydown', (e) => {
    if (e.key === 'ArrowRight') tabs[(i + 1) % tabs.length].focus()
    if (e.key === 'ArrowLeft') tabs[(i - 1 + tabs.length) % tabs.length].focus()
  })
})
</script>
20

列表组

基础列表组

list-group 是用于显示一系列内容的灵活组件。list-group-item 样式化每个条目。active 标记当前项目;disabled 使其变灰(使用 aria-disabled='true' 确保可访问性)。列表组比带样式的 div 对于相关内容列表(如仪表板、设置或收件箱项目)更具语义。导航列表使用 <ul>/<li>,非列表内容使用 <div>。

bootstrap
<!-- basic list group -->
<ul class="list-group">
  <li class="list-group-item">An item</li>
  <li class="list-group-item">A second item</li>
  <li class="list-group-item">A third item</li>
  <li class="list-group-item">A fourth item</li>
  <li class="list-group-item">A disabled item</li>
</ul>

<!-- with active item -->
<ul class="list-group">
  <li class="list-group-item active" aria-current="true">Active item</li>
  <li class="list-group-item">Regular item</li>
</ul>

<!-- disabled item -->
<ul class="list-group">
  <li class="list-group-item disabled" aria-disabled="true">Disabled</li>
</ul>

带链接和按钮的列表组

对于可操作的列表项(可点击),在 <a> 或 <button> 元素上使用 list-group-item-action。这添加了悬停和焦点状态。导航使用 <a>(带 href),操作使用 <button type='button'>。用 .disabled 类(和 aria-disabled)禁用链接;用 disabled 属性禁用按钮。避免在可操作项上使用 <li>——改用 <div> 作为 list-group 包装器,因为 <ul> 中的 <a>/<button> 语义性较差。

bootstrap
<!-- list group with links (actionable items) -->
<div class="list-group">
  <a href="#" class="list-group-item list-group-item-action active"
     aria-current="true">
    Active link item
  </a>
  <a href="#" class="list-group-item list-group-item-action">Link item</a>
  <a href="#" class="list-group-item list-group-item-action">Another link</a>
  <a class="list-group-item list-group-item-action disabled">Disabled link</a>
</div>

<!-- with buttons instead of links -->
<div class="list-group">
  <button type="button" class="list-group-item list-group-item-action active">
    Button item
  </button>
  <button type="button" class="list-group-item list-group-item-action">
    Another button
  </button>
</div>

<!-- note: use list-group-item-action for hover/focus states -->

列表组 Flush 与编号

list-group-flush 移除边框和圆角——用于嵌入卡片或容器中而没有双边框。list-group-numbered(在 <ol> 上)通过 CSS 计数器添加自动编号。list-group-horizontal 使项目并排放置;响应式变体(list-group-horizontal-md)在断点处切换为水平。水平列表适用于小型导航或筛选栏。编号列表非常适合分步说明或排名。

bootstrap
<!-- flush (no borders, no background, edge-to-edge) -->
<ul class="list-group list-group-flush">
  <li class="list-group-item">Flush item 1</li>
  <li class="list-group-item">Flush item 2</li>
  <li class="list-group-item">Flush item 3</li>
</ul>
<!-- removes outer borders and rounded corners -->

<!-- numbered list group (ordered) -->
<ol class="list-group list-group-numbered">
  <li class="list-group-item">First item</li>
  <li class="list-group-item">Second item</li>
  <li class="list-group-item">Third item</li>
</ol>
<!-- CSS counters add the numbers automatically -->

<!-- horizontal list group -->
<ul class="list-group list-group-horizontal">
  <li class="list-group-item">Item 1</li>
  <li class="list-group-item">Item 2</li>
  <li class="list-group-item">Item 3</li>
</ul>

<!-- responsive horizontal -->
<ul class="list-group list-group-horizontal-md">
  <!-- horizontal at md+, vertical below -->
</ul>

列表组上下文颜色与徽章

上下文类(list-group-item-{color})为项目着色用于状态指示——有意义地使用(success=完成,danger=错误)。对于列表项内的徽章,使用 d-flex justify-content-between align-items-center 将徽章推向右侧并垂直居中。rounded-pill 徽章对于计数看起来很现代。此模式是经典的收件箱/通知列表:左侧标签,右侧计数。flex 工具类无需自定义 CSS 即可处理对齐。

bootstrap
<!-- contextual color items -->
<ul class="list-group">
  <li class="list-group-item list-group-item-primary">Primary item</li>
  <li class="list-group-item list-group-item-secondary">Secondary</li>
  <li class="list-group-item list-group-item-success">Success</li>
  <li class="list-group-item list-group-item-danger">Danger</li>
  <li class="list-group-item list-group-item-warning">Warning</li>
  <li class="list-group-item list-group-item-info">Info</li>
  <li class="list-group-item list-group-item-light">Light</li>
  <li class="list-group-item list-group-item-dark">Dark</li>
</ul>

<!-- with badges (counts aligned right) -->
<ul class="list-group">
  <li class="list-group-item d-flex justify-content-between align-items-center">
    Messages
    <span class="badge bg-primary rounded-pill">14</span>
  </li>
  <li class="list-group-item d-flex justify-content-between align-items-center">
    Notifications
    <span class="badge bg-danger rounded-pill">3</span>
  </li>
  <li class="list-group-item d-flex justify-content-between align-items-center">
    Spam
    <span class="badge bg-warning text-dark rounded-pill">1</span>
  </li>
</ul>

列表组自定义内容

列表项可以包含丰富内容:标题(fw-bold)、描述(text-muted)、元数据(small)和徽章。使用 d-flex justify-content-between align-items-start 布局内容和徽章。me-auto 将徽章推向右侧。对于列表项中的复选框/单选按钮,使用 form-check-input 搭配匹配的 form-check-label——这创建可选择列表。常见用例:邮件列表、设置面板和搜索结果,每个项目都有标题、描述和状态。

bootstrap
<!-- rich content list item -->
<ul class="list-group">
  <li class="list-group-item d-flex justify-content-between align-items-start">
    <div class="ms-2 me-auto">
      <div class="fw-bold">Subheading</div>
      <p class="mb-0 text-muted">Descriptive text for the list item.</p>
      <small>Additional metadata</small>
    </div>
    <span class="badge bg-primary rounded-pill">New</span>
  </li>
  <li class="list-group-item d-flex justify-content-between align-items-start">
    <div class="ms-2 me-auto">
      <div class="fw-bold">Another item</div>
      <p class="mb-0">More content here.</p>
    </div>
    <span class="badge bg-secondary rounded-pill">3</span>
  </li>
</ul>

<!-- list group with checkbox/radio -->
<ul class="list-group">
  <li class="list-group-item">
    <input class="form-check-input me-1" type="checkbox" id="check1">
    <label class="form-check-label" for="check1">Checkbox item</label>
  </li>
  <li class="list-group-item">
    <input class="form-check-input me-1" type="radio" name="radio" id="radio1">
    <label class="form-check-label" for="radio1">Radio item</label>
  </li>
</ul>

这篇内容对您有帮助吗?

学习路径

从零开始学习

通过结构化课程从头学习这个语言。