如何用Bootstrap实现SVG图标居中、菜单文本及灰色文本靠右
解决方案
要实现下拉列表项里SVG图标垂直居中,同时让文本和说明在图标右侧,只需利用Bootstrap内置的flex布局类即可,无需额外自定义CSS。修改后的完整代码如下:
<!DOCTYPE html> <html> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <body> <div class="btn-group" role="group"> <button id="create" type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-plus-circle" viewBox="0 0 16 16"><path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/> <path d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z"/> </svg> Create new Workflow </button> <div class="dropdown-menu p-0 border-0" style="width: max-content;"> <a href="#" class="d-flex align-items-center p-2 list-group-item list-group-item-action" aria-current="true"> <svg xmlns="http://www.w3.org/2000/svg" height="32" width="25.6" class="me-3"><path d="M6.36 25.2h12.88v-2.4H6.36zm0-6.8h12.88V16H6.36zM2.4 32q-.96 0-1.68-.72Q0 30.56 0 29.6V2.4Q0 1.44.72.72 1.44 0 2.4 0h14.44l8.76 8.76V29.6q0 .96-.72 1.68-.72.72-1.68.72zM15.64 9.84V2.4H2.4v27.2h20.8V9.84zM2.4 2.4v7.44V2.4v27.2z" fill="#b69ee0"/></svg> <div> <span>Some placeholder content in a paragraph.</span> <br/> <small class="text-muted">And some small print.</small> </div> </a> <a href="#" class="d-flex align-items-center p-2 list-group-item list-group-item-action"> <div> <span>Some placeholder content in a paragraph.</span> <br/> <small class="text-muted">And some muted small print.</small> </div> </a> <a href="#" class="d-flex align-items-center p-2 list-group-item list-group-item-action"> <div> <span>Some placeholder content in a paragraph.</span> <br/> <small class="text-muted">And some muted small print.</small> </div> </a> </div> </div> </body> </html>
核心改动说明:
- 给下拉项的
<a>标签添加d-flex align-items-center:开启flex布局,让内部图标和文本自动垂直居中对齐。 - 给SVG图标添加
me-3:给图标右侧添加固定间距,避免和文本挤在一起。 - 把文本和灰色说明包裹在
<div>中:确保两行文本在图标右侧垂直堆叠,不会因换行跑到图标下方。
内容的提问来源于stack exchange,提问作者Code Guy
相关产品推荐
相关产品推荐

