Bootstrap如何让div内按钮在窗口缩放时始终保持同一行显示
解决方案
要实现按钮始终同行不换行,同时保证表格内容不溢出,只需做3处调整:
- 给包裹按钮的
.row容器添加flex-nowrap类,禁用flex默认的自动换行特性,可额外添加overflow-x: auto实现内容过宽时横向滚动,避免撑破容器 - 移除每个按钮外层div的
col-xs-6类,添加flex-shrink-0属性,避免按钮容器被压缩导致内容错位 - 给table添加
min-width属性,值可根据按钮总宽度自定义,保证表格缩小到该宽度后不再继续收缩,避免内容溢出
修改后的完整代码如下:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" /> <!-- 给table添加min-width,数值可根据实际需求调整 --> <table style="width:20%;min-width: 500px;"> <tr> <td id="123"> <!-- 给row添加flex-nowrap禁用自动换行 --> <div class='row ml-1 flex-nowrap' style="overflow-x: auto;"> <!-- 移除col-xs-6,添加flex-shrink-0避免容器被压缩 --> <div class='mr-1 mb-3 flex-shrink-0'> <button onclick='toggleHideShowTC(this.id)' id='33' title='Passed' class='btn btn-success rounded text-light font-weight-bold h6 p-1 d-inline-block'> 2331 ✓ </button> </div> <div class='mr-1 mb-3 flex-shrink-0'> <button onclick='toggleHideShowTC(this.id)' id='33' title='Passed' class='btn btn-success rounded text-light font-weight-bold h6 p-1 d-inline-block'> 2331 ✓ </button> </div> <div class='mr-1 mb-3 flex-shrink-0'> <button onclick='toggleHideShowTC(this.id)' id='33' title='Passed' class='btn btn-success rounded text-light font-weight-bold h6 p-1 d-inline-block'> 2331 ✓ </button> </div> <div class='mr-1 mb-3 flex-shrink-0'> <button onclick='toggleHideShowTC(this.id)' id='33' title='Passed' class='btn btn-success rounded text-light font-weight-bold h6 p-1 d-inline-block'> 2331 ✓ </button> </div> <div class='mr-1 mb-3 flex-shrink-0'> <button onclick='toggleHideShowTC(this.id)' id='33' title='Passed' class='btn btn-success rounded text-light font-weight-bold h6 p-1 d-inline-block'> 2331 ✓ </button> </div> </div> </td> </tr> </table>
预期效果示意:
修改后无论窗口如何缩放,所有按钮都会保持在同一行显示,表格缩小到设定的min-width阈值后就不会继续收缩,不会出现内容溢出问题。
内容的提问来源于stack exchange,提问作者Mads Sander Høgstrup
相关产品推荐
相关产品推荐

