Bootstrap 徽章/标签
Bootstrap 5 徽章 (Badges)
Section titled “Bootstrap 5 徽章 (Badges)”在 Bootstrap 5 中,“标签 (Labels)” 的概念已合并到 “徽章 (Badges)” 中。徽章是小巧的计数和标记组件,常用于突出显示新项目、通知数量或状态指示器。
徽章通过使用相对字体大小和 em 单位来匹配其直接父元素的尺寸。它们可以在标题、按钮内或独立使用。
<h1>Example heading <span class="badge bg-secondary">New</span></h1><h2>Example heading <span class="badge bg-primary">Updated</span></h2><h3>Example heading <span class="badge bg-success">Completed!</span></h3><p>Regular text with a <span class="badge bg-info text-dark">Info Badge</span>.</p>
<!-- 与旧版本 Bootstrap 的关键变化: - `.label` 类已移除。现在都使用 `.badge`。 - 上下文颜色使用背景工具类(例如 `bg-primary`, `bg-success`)或组合的 `text-bg-*` 类应用。 - 例如,旧的 `.label .label-default` 现在是 `<span class="badge bg-secondary">...</span>` 或 `<span class="badge text-bg-secondary">...</span>`。-->应用场景:在导航菜单中使用徽章显示未读消息,在产品卡片上突出显示“新品”或“促销”商品,或在列表中指示状态。
上下文徽章颜色
Section titled “上下文徽章颜色”使用 Bootstrap 的背景颜色工具类或组合的 text-bg-* 类来为徽章设置不同的颜色,传达语义。
Primary Secondary Success Danger Warning Info Light Dark
<span class="badge text-bg-primary me-1">Primary</span><span class="badge text-bg-secondary me-1">Secondary</span><span class="badge text-bg-success me-1">Success</span><span class="badge text-bg-danger me-1">Danger</span><span class="badge text-bg-warning me-1">Warning</span><span class="badge text-bg-info me-1">Info</span><span class="badge text-bg-light me-1">Light</span><span class="badge text-bg-dark me-1">Dark</span>
<!-- 使用 `text-bg-*` 类通常更简单,因为它们会自动处理文本对比度。 或者,使用单独的 `bg-*` 和 `text-*` 类: <span class="badge bg-primary text-white me-1">Primary (manual text color)</span>-->胶囊形徽章 (Pill Badges)
Section titled “胶囊形徽章 (Pill Badges)”为了获得更圆润、胶囊般的外观,除了 .badge 类外,使用 .rounded-pill 工具类。
Primary Pill Secondary Pill Success Pill
<span class="badge rounded-pill text-bg-primary me-1">Primary Pill</span><span class="badge rounded-pill text-bg-secondary me-1">Secondary Pill</span><span class="badge rounded-pill text-bg-success me-1">99+</span><span class="badge rounded-pill text-bg-danger position-relative me-3"> Notifications <span class="position-absolute top-0 start-100 translate-middle badge border border-light rounded-circle bg-warning p-2"><span class="visually-hidden">unread messages</span></span></span>
<!-- 最后一个示例展示了一个相对于文本定位的更复杂的通知徽章。 -->按钮中的徽章
Section titled “按钮中的徽章”徽章可以轻松地放在按钮内部,用作计数器或指示器。
Messages 4
<button type="button" class="btn btn-primary"> Notifications <span class="badge text-bg-secondary ms-1">4</span></button>
<button type="button" class="btn btn-outline-danger position-relative"> Inbox <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger"> 99+ <span class="visually-hidden">unread messages</span> </span></button>
<!-- 提示:使用外边距工具类,如 `ms-1`(margin-start,左外边距),在按钮文本和徽章之间添加一点空间。 第二个示例使用定位工具类,使通知徽章位于按钮正常流的外部,更加醒目。 `.visually-hidden` 用于可访问性,如果徽章只是一个数字,它为屏幕阅读器提供关于徽章含义的上下文。-->应用场景:按钮上的徽章常用于用户界面中,显示消息计数、购物车项目数量或待处理任务指示。
在 Bootstrap 5 官方文档中探索所有徽章功能,包括定位和可访问性注意事项:https://getbootstrap.com/docs/5.3/components/badge/