案例 按钮/图标
Bootstrap 5 案例研究:添加按钮和图标
Section titled “Bootstrap 5 案例研究:添加按钮和图标”添加样式化按钮
Section titled “添加样式化按钮”Bootstrap 的按钮类(button classes)可以应用于 <a>、<button> 或 <input type="button">(以及类似类型的)元素,以快速创建带有样式的按钮。
Bootstrap 3 中的 Jumbotron 组件在 Bootstrap 5 中已被移除。但是,您可以使用实用类(utility classes)实现类似的突出行动号召(call-to-action)区域。让我们创建一个包含一个大型、蓝色信息按钮的区域。
我们将使用 .btn 用于基本按钮样式,.btn-info 用于蓝色,以及 .btn-lg 用于更大的尺寸。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Bootstrap Button Example</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"></head><body> <div class="container py-4"> <div class="p-5 mb-4 bg-light rounded-3"> <div class="container-fluid py-5"> <h1 class="display-5 fw-bold">My Modern Bootstrap Page!</h1> <p class="col-md-8 fs-4">This page showcases Bootstrap 5 components and utilities, demonstrating modern web design practices.</p> <a class="btn btn-info btn-lg" href="#" role="button">Learn more</a> </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script></body></html>为什么使用 href="#"?在开发阶段,如果一个链接还没有指向一个实际页面,href="#" 是一个常见的占位符。它能防止页面重新加载或导航错误。在实际应用中,应将其替换为一个有效的 URL。为 <a/> 标签添加 role="button" 并将其样式化为按钮,是为了更好的可访问性。
为按钮添加图标
Section titled “为按钮添加图标”Bootstrap 5 不再包含 Glyphicons。相反,它推荐使用外部图标库,如 Bootstrap Icons、Font Awesome 或自定义 SVGs。
让我们使用 Bootstrap Icons 为按钮添加一个搜索图标。首先,您需要在项目中包含 Bootstrap Icons 的 CSS(例如,通过 CDN:<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">)。
要显示一个 Bootstrap Icon,使用一个 <i> 标签并为其指定相应的图标类,例如 <i class="bi bi-search"></i> 用于搜索图标。
为按钮添加搜索图标的示例:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Bootstrap Button with Icon</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css"></head><body> <div class="container py-4"> <div class="p-5 mb-4 bg-light rounded-3"> <div class="container-fluid py-5"> <h1 class="display-5 fw-bold">My Modern Bootstrap Page!</h1> <p class="col-md-8 fs-4">Explore the features and learn more about what we offer.</p> <a class="btn btn-primary btn-lg" href="#" role="button"> <i class="bi bi-search"></i> Search Content </a> </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script></body></html>应用场景:首页上的行动号召按钮,例如“注册 ”,使用图标可以直观地加强按钮的用途并吸引用户注意。
常见陷阱:忘记包含图标库的 CSS。如果图标没有显示,请检查 Bootstrap Icons(或您选择的其他库)的样式表是否正确链接在 HTML 的 <head> 中。