bootstrap_ref_comp_glyphs
Bootstrap 5:使用图标(替代 Glyphicons)
Section titled “Bootstrap 5:使用图标(替代 Glyphicons)”Bootstrap 版本 4 和 5 不再包含 Glyphicons 字体图标或其他任何内置的图标集。这一改变鼓励开发者使用更灵活、更现代的解决方案,例如 SVG 图标。
核心思想保持不变:图标通过提供视觉线索来增强用户界面(UI)。本指南将展示如何将流行的图标库与 Bootstrap 5 集成。
推荐的图标解决方案
Section titled “推荐的图标解决方案”虽然您可以使用任何图标库,但 Bootstrap 官方推荐其自身的 Bootstrap Icons 图标库。其他流行的选择包括 Font Awesome 或自定义 SVG。
- 可伸缩性:SVG 在任何尺寸下都保持清晰。
- 自定义性:使用 CSS 可以轻松改变颜色、描边和其他属性。
- 可访问性:通过适当的 ARIA 属性和标题,SVG 可以变得更易于访问。
- 性能:通常比字体图标性能更好,特别是只使用少量图标时。
使用 Bootstrap Icons
Section titled “使用 Bootstrap Icons”Bootstrap Icons(https://icons.getbootstrap.com/)是 Bootstrap 官方的开源图标库。您可以通过以下几种方式将其包含到项目中:
- CDN 链接 (CSS): 最快的入门方式。将 Bootstrap Icons CSS 链接添加到 HTML 的
<head>中。 - NPM 安装: 对于使用构建过程的项目(
npm install bootstrap-icons)。 - 内联 SVG: 将 SVG 代码直接复制到您的 HTML 中。
- SVG Sprite: 使用 SVG Sprite 在使用大量图标时获得更好的性能。
示例:通过 CDN 包含 Bootstrap Icons 并使用 CSS 类:
<!-- 1. 将此代码添加到 <head> 中 --><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
<!-- 2. 在 HTML 中使用图标 --><p> Envelope icon: <i class="bi bi-envelope-fill"></i></p><p> Search icon: <i class="bi bi-search"></i></p><button type="button" class="btn btn-primary"> <i class="bi bi-printer-fill"></i> Print Document</button>
<p> Calendar icon with custom size and color: <i class="bi bi-calendar-event" style="font-size: 2rem; color: cornflowerblue;"></i></p>
<!-- 提示:您可以使用 CSS 的 font-size 和 color 属性,或 Bootstrap 的文本工具类来设置图标的样式(大小、颜色)。 -->示例:使用内联 SVG(来自 Bootstrap Icons):
<p> Heart icon (embedded SVG): <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-heart-fill text-danger" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M8 1.314C12.438-3.248 23.534 4.735 8 15-7.534 4.736 3.562-3.248 8 1.314z"/> </svg></p>
<!-- 注意:通常您会从 Bootstrap Icons 网站复制所需图标的 SVG 代码。 `width`、`height` 和 `fill="currentColor"` 属性对于正确显示和继承 CSS 颜色非常重要。 如果需要统一风格,添加像 `bi` 这样的类也很有用。-->图标选项概览
Section titled “图标选项概览”下表总结了在 Bootstrap 5 中使用图标的常见方法:
| 图标解决方案 | 主要使用方法 | 示例(概念性) | 在哪里找到/了解更多 |
|---|---|---|---|
| Bootstrap Icons | CSS 类(通过 CDN/NPM)、内联 SVG、SVG Sprite | <i class="bi bi-alarm"></i> 或 <svg>...</svg> | 官方网站:icons.getbootstrap.com |
| Font Awesome | CSS 类(设置后)、带 JS 的 SVG | <i class="fas fa-heart"></i> 或 <svg class="svg-inline--fa">...</svg> | 官方网站:fontawesome.com |
| 其他 SVG 库(例如 Feather Icons、Material Icons) | 不同(通常是内联 SVG、CSS 类或 JS 组件) | 取决于具体的库 | 搜索特定的库(例如,“Feather Icons”、“Material Design Icons”) |
| 自定义 SVGs | 直接内联 <svg> 代码,使用带有 SVG 源的 <img> 标签,或创建 SVG Sprite | <svg>...</svg> 或 <img src="path/to/icon.svg" alt="Description"> | 使用矢量图形编辑器(Illustrator、Inkscape、Figma)创建,或从图标市场下载。 |
关键要点:虽然 Bootstrap 不捆绑图标,但它完全支持现代的图标使用方式。选择最适合您项目需求和工作流程的解决方案。
关于图标可访问性的更多指导,请参考以下资源:https://www.w3.org/WAI/tutorials/images/icons/