bootstrap-components
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseBootstrap 5.3 Components
Bootstrap 5.3 Components
Bootstrap provides ready-to-use UI components for building interfaces. This skill covers all major components with usage patterns, JavaScript initialization requirements, and accessibility best practices.
JavaScript Initialization Overview: Some components work purely with data attributes, while others require JavaScript initialization. Components marked with Requires JS below won't function without explicit initialization.
| Component | Requires JS Init | Data Attributes Only |
|---|---|---|
| Tooltip | Yes | No |
| Popover | Yes | No |
| Toast | Yes (to show) | No |
| Scrollspy | Optional | Yes |
| Modal | Optional | Yes |
| Carousel | Optional | Yes |
| Collapse | Optional | Yes |
| Dropdown | Optional | Yes |
Bootstrap提供了可直接使用的UI组件,用于构建界面。本技能涵盖所有主要组件的使用模式、JavaScript初始化要求以及无障碍最佳实践。
JavaScript初始化概述: 部分组件仅通过数据属性即可工作,而其他组件则需要JavaScript初始化。下方标记为Requires JS的组件如果不进行显式初始化将无法正常运行。
| 组件 | 需要JS初始化 | 仅需数据属性 |
|---|---|---|
| Tooltip | 是 | 否 |
| Popover | 是 | 否 |
| Toast | 是(用于显示) | 否 |
| Scrollspy | 可选 | 是 |
| Modal | 可选 | 是 |
| Carousel | 可选 | 是 |
| Collapse | 可选 | 是 |
| Dropdown | 可选 | 是 |
Interactive Components
交互式组件
These components require or benefit from JavaScript. See for detailed code examples, JavaScript APIs, and accessibility guidance.
references/interactive-components.md这些组件需要或受益于JavaScript。如需详细代码示例、JavaScript API及无障碍指南,请查看。
references/interactive-components.mdAccordion
Accordion
Collapsible content panels that show one section at a time. Use wrapper with children containing and . Remove to allow multiple panels open simultaneously. Use for borderless variant.
.accordion.accordion-item.accordion-header.accordion-collapsedata-bs-parent.accordion-flush可折叠的内容面板,一次仅显示一个区域。使用容器包裹包含和的子元素。移除可允许多个面板同时展开。使用可实现无边框变体。
.accordion.accordion-header.accordion-collapse.accordion-itemdata-bs-parent.accordion-flushCarousel
Carousel
Image slideshow with optional controls and indicators. Use wrapper with containing slides. Add / for navigation. Use for autoplay. Respects automatically.
.carousel.slide.carousel-inner.carousel-item.carousel-control-prev.carousel-control-nextdata-bs-ride="carousel"prefers-reduced-motion带有可选控件和指示器的图片轮播组件。使用容器包裹包含幻灯片的。添加/用于导航。使用启用自动播放。组件会自动遵循设置。
.carousel.slide.carousel-item.carousel-inner.carousel-control-prev.carousel-control-nextdata-bs-ride="carousel"prefers-reduced-motionCollapse
Collapse
Toggle content visibility with smooth animations. Use on trigger with pointing to element. Use for width-based collapse. Target multiple elements with class selector ().
data-bs-toggle="collapse"data-bs-target.collapse.collapse-horizontal.multi-collapse通过平滑动画切换内容的可见性。在触发元素上使用,并通过指向元素。使用实现基于宽度的折叠效果。可通过类选择器()指向多个元素。
data-bs-toggle="collapse"data-bs-target.collapse.collapse-horizontal.multi-collapseDropdowns
Dropdowns
Toggleable contextual menus for links and actions. Use wrapper with button and list. Direction variants: , , . Add for dark theme. Keyboard navigation is built-in.
.dropdown.dropdown-toggle.dropdown-menu.dropup.dropend.dropstart.dropdown-menu-dark用于链接和操作的可切换上下文菜单。使用容器包裹按钮和列表。方向变体:、、。添加启用深色主题。组件内置键盘导航支持。
.dropdown.dropdown-toggle.dropdown-menu.dropup.dropend.dropstart.dropdown-menu-darkModal
Modal
Dialog boxes that overlay the page and trap focus. Use with pointing to element. Sizes: , , . Modifiers: , . Use to prevent dismiss on outside click.
data-bs-toggle="modal"data-bs-target.modal.modal-sm.modal-lg.modal-xl.modal-dialog-centered.modal-dialog-scrollabledata-bs-backdrop="static"覆盖页面并锁定焦点的对话框。使用,并通过指向元素。尺寸选项:、、。修饰类:、。使用可防止点击外部关闭模态框。
data-bs-toggle="modal"data-bs-target.modal.modal-sm.modal-lg.modal-xl.modal-dialog-centered.modal-dialog-scrollabledata-bs-backdrop="static"Offcanvas
Offcanvas
Hidden sidebars that slide from viewport edge. Positions: (left), (right), , . Use to allow body scrolling. Use for persistent sidebars.
.offcanvas-start.offcanvas-end.offcanvas-top.offcanvas-bottomdata-bs-scroll="true"data-bs-backdrop="static"从视口边缘滑出的隐藏侧边栏。位置选项:(左侧)、(右侧)、、。使用允许页面主体滚动。使用实现持久化侧边栏。
.offcanvas-start.offcanvas-end.offcanvas-top.offcanvas-bottomdata-bs-scroll="true"data-bs-backdrop="static"Popovers
Popovers
Requires JS init and Popper.js. Rich overlay content triggered by click or hover. Use with and . Initialize with or batch initialize all: . Placements: top, right, bottom, left. Use (includes Popper) or include Popper separately before .
data-bs-toggle="popover"data-bs-titledata-bs-contentnew bootstrap.Popover(el)document.querySelectorAll('[data-bs-toggle="popover"]').forEach(el => new bootstrap.Popover(el))bootstrap.bundle.jsbootstrap.js需要JS初始化和Popper.js。 由点击或悬停触发的富内容覆盖层。使用,并配合和。通过初始化单个组件,或批量初始化所有组件:。位置选项:top、right、bottom、left。可使用(已包含Popper),或在之前单独引入Popper。
data-bs-toggle="popover"data-bs-titledata-bs-contentnew bootstrap.Popover(el)document.querySelectorAll('[data-bs-toggle="popover"]').forEach(el => new bootstrap.Popover(el))bootstrap.bundle.jsbootstrap.jsScrollspy
Scrollspy
Auto-update navigation based on scroll position. Use on scrollable container with pointing to nav. Use to control activation threshold. Container needs so keyboard-only users can focus and scroll the container without a mouse.
data-bs-spy="scroll"data-bs-targetdata-bs-root-margintabindex="0"根据滚动位置自动更新导航的组件。在可滚动容器上使用,并通过指向导航元素。使用控制激活阈值。容器需要设置,以便纯键盘用户无需鼠标即可聚焦并滚动容器。
data-bs-spy="scroll"data-bs-targetdata-bs-root-margintabindex="0"Toasts
Toasts
Requires JS to show. Lightweight dismissible notifications. Use for positioning and stacking. Initialize with then call . Options: , . Placements via container positioning classes.
.toast-containernew bootstrap.Toast(el).show()autohide: truedelay: 5000需要JS触发显示。 轻量级可关闭通知组件。使用进行定位和堆叠。通过初始化后调用显示。配置选项:、。通过容器的定位类控制显示位置。
.toast-containernew bootstrap.Toast(el).show()autohide: truedelay: 5000Tooltips
Tooltips
Requires JS init and Popper.js. Hover hints for brief descriptions. Use with (preferred) or attribute. Initialize with or batch initialize all: . Placements: top, right, bottom, left. Tooltips on disabled buttons require a wrapper or with for keyboard accessibility. Use (includes Popper) or include Popper separately before .
data-bs-toggle="tooltip"data-bs-titletitlenew bootstrap.Tooltip(el)document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(el => new bootstrap.Tooltip(el))<span><div>tabindex="0"bootstrap.bundle.jsbootstrap.js需要JS初始化和Popper.js。 用于简短说明的悬停提示。使用,并优先使用而非属性。通过初始化单个组件,或批量初始化所有组件:。位置选项:top、right、bottom、left。禁用按钮上的tooltip需要使用或包裹,并设置以保证键盘无障碍。可使用(已包含Popper),或在之前单独引入Popper。
data-bs-toggle="tooltip"data-bs-titletitlenew bootstrap.Tooltip(el)document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(el => new bootstrap.Tooltip(el))<span><div>tabindex="0"bootstrap.bundle.jsbootstrap.jsStatic Components
静态组件
These components work primarily with CSS and HTML. See for detailed code examples and accessibility guidance.
references/static-components.md这些组件主要通过CSS和HTML工作。如需详细代码示例及无障碍指南,请查看。
references/static-components.mdAlerts
Alerts
Contextual feedback messages. Use with . Colors: primary, secondary, success, danger, warning, info, light, dark. Use for styled links. Add with close button for dismissible alerts.
.alert.alert-{color}role="alert".alert-link.alert-dismissible上下文反馈消息。使用并设置。颜色选项:primary、secondary、success、danger、warning、info、light、dark。使用设置样式化链接。添加及关闭按钮可实现可关闭的提示框。
.alert.alert-{color}role="alert".alert-link.alert-dismissibleBadges
Badges
Labels, counters, and status indicators. Use on . Use for pill shape. Position with utilities for notification badges. Include text for screen reader context.
.badge.bg-{color}<span>.rounded-pill.position-absolute.visually-hidden标签、计数器和状态指示器。在上使用。使用实现胶囊形状。通过工具类设置通知徽章的位置。添加文本为屏幕阅读器提供上下文信息。
<span>.badge.bg-{color}.rounded-pill.position-absolute.visually-hiddenBreadcrumb
Breadcrumb
Navigation hierarchy indicator. Wrap in . Use on elements. Mark current page with and . Customize divider via CSS variable.
<ol class="breadcrumb"><nav aria-label="breadcrumb">.breadcrumb-item<li>.activearia-current="page"--bs-breadcrumb-divider导航层级指示器。将包裹在中。在元素上使用。使用和标记当前页面。可通过CSS变量自定义分隔符。
<ol class="breadcrumb"><nav aria-label="breadcrumb"><li>.breadcrumb-item.activearia-current="page"--bs-breadcrumb-dividerButtons
Buttons
Interactive button elements. Base: . Outline: . Sizes: , . Full width: wrap in . States: attribute, class. Use for actions, for navigation.
.btn.btn-{color}.btn-outline-{color}.btn-lg.btn-sm.d-griddisabled.active<button><a>交互式按钮元素。基础样式:。轮廓样式:。尺寸选项:、。全宽按钮:包裹在中。状态:属性、类。操作类按钮使用,导航类按钮使用。
.btn.btn-{color}.btn-outline-{color}.btn-lg.btn-sm.d-griddisabled.active<button><a>Button Group
Button Group
Related buttons grouped together. Use with and . Vertical: . Toolbar: wrapper with . Sizes: , .
.btn-grouprole="group"aria-label.btn-group-vertical.btn-toolbarrole="toolbar".btn-group-lg.btn-group-sm相关按钮组合在一起。使用并设置和。垂直分组:。工具栏:使用容器并设置。尺寸选项:、。
.btn-grouprole="group"aria-label.btn-group-vertical.btn-toolbarrole="toolbar".btn-group-lg.btn-group-smCards
Cards
Flexible content containers. Structure: > > , . Optional: , , /. Grid layout: use with > for equal heights.
.card.card-body.card-title.card-text.card-header.card-footer.card-img-top.card-img-bottom.row.row-cols-{n}.col.card.h-100灵活的内容容器。结构: > > 、。可选部分:、、/。网格布局:使用配合 > 实现等高卡片。
.card.card-body.card-title.card-text.card-header.card-footer.card-img-top.card-img-bottom.row.row-cols-{n}.col.card.h-100Close Button
Close Button
Generic dismiss button. Use with . White variant: . Dismiss targets via .
.btn-closearia-label="Close".btn-close-whitedata-bs-dismiss="alert|modal|offcanvas|toast"通用关闭按钮。使用并设置。白色变体:。通过指定关闭目标。
.btn-closearia-label="Close".btn-close-whitedata-bs-dismiss="alert|modal|offcanvas|toast"List Group
List Group
Series of content items as lists. Use > . Actionable: add . Borderless: . Horizontal: . Colors: .
.list-group.list-group-item.list-group-item-action.list-group-flush.list-group-horizontal.list-group-item-{color}以列表形式展示的系列内容项。使用 > 。可交互项:添加。无边框:。水平布局:。颜色选项:。
.list-group.list-group-item.list-group-item-action.list-group-flush.list-group-horizontal.list-group-item-{color}Navbar
Navbar
Responsive navigation header. Use . Contains , , . Placement: , , . Theme: ( deprecated in v5.3).
.navbar.navbar-expand-{breakpoint}.navbar-brand.navbar-toggler.navbar-collapse.fixed-top.fixed-bottom.sticky-topdata-bs-theme="dark".navbar-light响应式导航头部。使用。包含、、。定位选项:、、。主题:(v5.3中已弃用)。
.navbar.navbar-expand-{breakpoint}.navbar-brand.navbar-toggler.navbar-collapse.fixed-top.fixed-bottom.sticky-topdata-bs-theme="dark".navbar-lightNavs and Tabs
Navs and Tabs
Base navigation with visual styles. Styles: , , . Layout: (equal width), (full width), (vertical). For tabbed content, use with buttons and panes.
.nav-tabs.nav-pills.nav-underline.nav-fill.nav-justified.flex-columnrole="tablist"role="tab"role="tabpanel"带有视觉样式的基础导航。样式选项:、、。布局选项:(等宽)、(全宽)、(垂直)。对于标签页内容,使用配合按钮和面板。
.nav-tabs.nav-pills.nav-underline.nav-fill.nav-justified.flex-columnrole="tablist"role="tab"role="tabpanel"Pagination
Pagination
Navigation for paginated content. Use > > > . Sizes: , . Alignment: , . Mark current: with .
<nav aria-label="...">.pagination.page-item.page-link.pagination-lg.pagination-sm.justify-content-center.justify-content-end.activearia-current="page"分页内容的导航组件。使用 > > > 。尺寸选项:、。对齐方式:、。标记当前页:配合。
<nav aria-label="...">.pagination.page-item.page-link.pagination-lg.pagination-sm.justify-content-center.justify-content-end.activearia-current="page"Placeholders
Placeholders
Loading state indicators. Use spans with column widths (). Animations: wrap in or . Sizes: , , . Add to placeholder containers.
.placeholder.col-6.placeholder-glow.placeholder-wave.placeholder-lg.placeholder-sm.placeholder-xsaria-hidden="true"加载状态指示器。在上使用并配合列宽类()。动画效果:包裹在或中。尺寸选项:、、。在占位容器上添加。
<span>.placeholder.col-6.placeholder-glow.placeholder-wave.placeholder-lg.placeholder-sm.placeholder-xsaria-hidden="true"Progress
Progress
Progress indicators for tasks. Use wrapper with inside. Set width via . Variants: , . Colors: . Include ARIA attributes: , , , .
.progress.progress-barstyle="width: X%".progress-bar-striped.progress-bar-animated.bg-{color}role="progressbar"aria-valuenowaria-valueminaria-valuemax任务进度指示器。使用容器包裹内部的。通过设置宽度。变体:、。颜色选项:。添加ARIA属性:、、、。
.progress.progress-barstyle="width: X%".progress-bar-striped.progress-bar-animated.bg-{color}role="progressbar"aria-valuenowaria-valueminaria-valuemaxSpinners
Spinners
Loading indicators. Types: (spinning), (pulsing). Sizes: , . Colors: . Include and loading text.
.spinner-border.spinner-grow.spinner-border-sm.spinner-grow-sm.text-{color}role="status".visually-hidden加载指示器。类型:(旋转)、(脉冲)。尺寸选项:、。颜色选项:。添加及加载文本。
.spinner-border.spinner-grow.spinner-border-sm.spinner-grow-sm.text-{color}role="status".visually-hiddenCommon Gotchas & Tips
常见问题与技巧
Components Requiring JavaScript Initialization
需要JavaScript初始化的组件
Tooltips and popovers will not work without explicit JavaScript initialization. Unlike modals, dropdowns, and carousels (which work via data attributes), these components must be initialized:
javascript
// Initialize all tooltips
document.querySelectorAll('[data-bs-toggle="tooltip"]')
.forEach(el => new bootstrap.Tooltip(el));
// Initialize all popovers
document.querySelectorAll('[data-bs-toggle="popover"]')
.forEach(el => new bootstrap.Popover(el));Toasts also require JavaScript to show—they are hidden by default and must be shown programmatically with .
toast.show()Tooltip和popover如果不进行显式JavaScript初始化将无法工作。与modal、dropdown和carousel(可通过数据属性工作)不同,这些组件必须初始化:
javascript
// 初始化所有tooltips
document.querySelectorAll('[data-bs-toggle="tooltip"]')
.forEach(el => new bootstrap.Tooltip(el));
// 初始化所有popovers
document.querySelectorAll('[data-bs-toggle="popover"]')
.forEach(el => new bootstrap.Popover(el));Toast也需要JavaScript触发显示——它们默认隐藏,必须通过以编程方式显示。
toast.show()Tooltip/Popover Positioning Issues
Tooltip/Popover定位问题
If tooltips or popovers appear in the wrong position, get clipped, or behave strangely in complex layouts (input groups, button groups, tables, modals), use :
container: 'body'javascript
// Append to body to avoid rendering issues
new bootstrap.Tooltip(el, { container: 'body' });
new bootstrap.Popover(el, { container: 'body' });For popovers inside modals, set to the modal body so focus remains trapped:
containerjavascript
new bootstrap.Popover(el, { container: '.modal-body' });如果tooltip或popover出现位置错误、被截断,或在复杂布局(输入组、按钮组、表格、模态框)中表现异常,可使用:
container: 'body'javascript
// 追加到body以避免渲染问题
new bootstrap.Tooltip(el, { container: 'body' });
new bootstrap.Popover(el, { container: 'body' });对于模态框内的popover,将设置为模态框主体,以确保焦点被正确锁定:
containerjavascript
new bootstrap.Popover(el, { container: '.modal-body' });Modal Best Practices
Modal最佳实践
Semantic headings: Bootstrap recommends using for modal titles semantically (the modal represents its own document context). Use font size utilities like to control visual appearance while maintaining proper heading hierarchy.
<h1>.fs-5Autofocus workaround: The HTML attribute has no effect in Bootstrap modals due to HTML5 semantics. To focus an input when a modal opens:
autofocusjavascript
myModal.addEventListener('shown.bs.modal', () => {
document.getElementById('myInput').focus();
});Nested modals: Bootstrap only supports one modal at a time. Nested modals are not supported and considered poor user experience. If multiple dialogs are needed, close the current modal before opening another.
Dynamic content height: After dynamically changing modal body content that affects height, call to readjust the modal's position.
modal.handleUpdate()语义化标题:Bootstrap建议在模态框标题中使用(模态框代表独立的文档上下文)。可使用等字体大小工具类控制视觉样式,同时保持正确的标题层级。
<h1>.fs-5自动聚焦解决方案:由于HTML5语义限制,HTML的属性在Bootstrap模态框中无效。如需在模态框打开时聚焦输入框:
autofocusjavascript
myModal.addEventListener('shown.bs.modal', () => {
document.getElementById('myInput').focus();
});嵌套模态框:Bootstrap仅支持同时显示一个模态框。嵌套模态框不受支持,且被认为是糟糕的用户体验。如果需要多个对话框,应先关闭当前模态框再打开新的。
动态内容高度:在动态修改模态框主体内容并影响高度后,调用重新调整模态框的位置。
modal.handleUpdate()Cross-Component Patterns
跨组件模式
Modals with forms: Place form validation feedback inside the modal body. On successful submission, call and optionally show a toast notification.
modal.hide()Toast stacking: Use with positioning utilities () for consistent toast placement. Multiple toasts stack automatically.
.toast-container.position-fixed.bottom-0.end-0.p-3Navbar with offcanvas: For mobile navigation, combine with offcanvas for a sliding menu. Use on the navbar toggler instead of collapse for a different UX pattern.
.navbardata-bs-toggle="offcanvas"Cards in grids: Use with > to create equal-height card grids that respond to breakpoints.
.row.row-cols-{n}.col.card.h-100带表单的模态框:将表单验证反馈放在模态框主体内。提交成功后,调用并可选择显示toast通知。
modal.hide()Toast堆叠:使用配合定位工具类()实现一致的toast定位。多个toast会自动堆叠。
.toast-container.position-fixed.bottom-0.end-0.p-3搭配Offcanvas的Navbar:对于移动端导航,可将与Offcanvas结合实现滑动菜单。在导航栏切换按钮上使用而非collapse,以提供不同的用户体验模式。
.navbardata-bs-toggle="offcanvas"网格中的卡片:使用配合 > 创建等高卡片网格,且可响应断点变化。
.row.row-cols-{n}.col.card.h-100Additional Resources
额外资源
Reference Files
参考文件
- - Quick reference tables for all component classes
references/components-reference.md - - CSS custom properties for runtime component theming
references/css-custom-properties.md - - Detailed documentation for JS-dependent components
references/interactive-components.md - - Detailed documentation for CSS/HTML components
references/static-components.md
- - 所有组件类的快速参考表格
references/components-reference.md - - 用于运行时组件主题定制的CSS自定义属性
references/css-custom-properties.md - - 依赖JS的组件详细文档
references/interactive-components.md - - CSS/HTML组件详细文档
references/static-components.md
Example Files
示例文件
- - Accordion and FAQ patterns
examples/accordion-patterns.html - - Alert variants, dismissible alerts, live region patterns
examples/alert-patterns.html - - Badges, buttons, button groups, and close buttons
examples/badge-button-patterns.html - - Breadcrumb navigation with custom dividers and icons
examples/breadcrumb-patterns.html - - Responsive card grid layouts
examples/card-grid-patterns.html - - Carousel implementation patterns
examples/carousel-patterns.html - - Collapse, horizontal collapse, and multi-target patterns
examples/collapse-patterns.html - - Dropdown menus, split buttons, and form dropdowns
examples/dropdown-patterns.html - - List groups, actionable items, and tab integration
examples/list-group-patterns.html - - Modal dialog patterns
examples/modal-patterns.html - - Navigation bar layouts
examples/navbar-patterns.html - - Offcanvas sidebar patterns
examples/offcanvas-patterns.html - - Pagination variants, alignment, and responsive patterns
examples/pagination-patterns.html - - Loading skeleton patterns for cards, lists, and tables
examples/placeholder-patterns.html - - Tooltip and popover patterns (requires JS init)
examples/popovers-tooltips-patterns.html - - Progress bars and spinner loading indicators
examples/progress-spinner-patterns.html - - Scrollspy with navbar, list group, and documentation patterns
examples/scrollspy-patterns.html - - Tab navigation patterns
examples/tabs-patterns.html - - Toast notification patterns (requires JS init)
examples/toasts-patterns.html
- - 手风琴和FAQ模式
examples/accordion-patterns.html - - 提示框变体、可关闭提示框、实时区域模式
examples/alert-patterns.html - - 徽章、按钮、按钮组和关闭按钮
examples/badge-button-patterns.html - - 面包屑导航(含自定义分隔符和图标)
examples/breadcrumb-patterns.html - - 响应式卡片网格布局
examples/card-grid-patterns.html - - 轮播组件实现模式
examples/carousel-patterns.html - - 折叠、水平折叠和多目标折叠模式
examples/collapse-patterns.html - - 下拉菜单、分割按钮和表单下拉框
examples/dropdown-patterns.html - - 列表组、可交互项和标签页集成
examples/list-group-patterns.html - - 模态框对话框模式
examples/modal-patterns.html - - 导航栏布局
examples/navbar-patterns.html - - 侧边栏抽屉模式
examples/offcanvas-patterns.html - - 分页变体、对齐方式和响应式模式
examples/pagination-patterns.html - - 卡片、列表和表格的加载骨架模式
examples/placeholder-patterns.html - - Tooltip和Popover模式(需要JS初始化)
examples/popovers-tooltips-patterns.html - - 进度条和加载指示器
examples/progress-spinner-patterns.html - - 搭配Navbar、列表组和文档的Scrollspy模式
examples/scrollspy-patterns.html - - 标签导航模式
examples/tabs-patterns.html - - Toast通知模式(需要JS初始化)
examples/toasts-patterns.html