如何让Bootstrap徽章并排且与上下徽章宽度一致?
解决Bootstrap徽章各占50%宽度并排的问题
你的核心问题是当前CSS给徽章设置了固定宽度150px,限制了它的自适应能力,同时徽章默认的内联特性没有让它占满父容器。按以下步骤修改即可实现目标效果:
1. 修改CSS样式
把固定宽度改为100%,让徽章继承父元素的宽度,同时保留溢出截断的特性:
.tgr_card span.badge { display: block; width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center; /* 可选:让徽章内文字居中,更贴合视觉效果 */ }
注意把选择器改成
.tgr_card span.badge,避免影响其他非徽章的span元素。
2. 优化HTML结构
可以用Bootstrap的弹性布局类直接包裹两个徽章,通过flex-grow-1实现平分宽度,同时保持和左侧文字的间距:
<li class="list-group-item d-flex justify-content-between align-items-center"> Min Max <div class="d-flex gap-2 w-100 ms-2"> <span class="badge bg-primary rounded-2 flex-grow-1">1</span> <span class="badge bg-primary rounded-2 flex-grow-1">None</span> </div> </li>
如果继续使用row/col结构,只需确保徽章宽度设为100%,也能达到相同效果,两种方式都符合Bootstrap语义化规范。
完整修改后的代码示例
CSS
.tgr_card span.badge { display: block; width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center; }
HTML
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>test</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.3/font/bootstrap-icons.css"> <style> .tgr_card span.badge { display: block; width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center; } </style> </head> <body> <div class="card tgr_card" style="width: 30rem;"> <div class="card-body"> <h5 class="card-title d-flex justify-content-between align-items-center"> Name <div class="text-end"> <button type="button" class="btn-close" aria-label="Close"></button> </div> </h5> <h6 class="card-subtitle mb-2 text-muted">#x</h6> <br> <ul class="list-group list-group-flush tgr_card_ul"> <li class="list-group-item d-flex justify-content-between align-items-center"> Name <span class="badge bg-primary rounded-2">test</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> Min Max <div class="d-flex gap-2 w-100 ms-2"> <span class="badge bg-primary rounded-2 flex-grow-1">1</span> <span class="badge bg-primary rounded-2 flex-grow-1">None</span> </div> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> Name <span class="badge bg-primary rounded-2">test</span> </li> </ul> </div> <div class="card-footer text-muted text-center"> <a href="#" class="btn btn-primary" style="width: 100%;">footer</a> </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script> </body> </html>
修改后,两个徽章会平分容器宽度,和上下的全宽徽章保持视觉统一,同时保留文字溢出截断的功能。
内容的提问来源于stack exchange,提问作者user20925063
相关产品推荐
相关产品推荐

