如何使用Bootstrap使两列中的按钮水平对齐至同一高度
实现两列按钮水平对齐至同一高度的Bootstrap方案
核心思路
借助Bootstrap的弹性布局类,将每一列设置为垂直方向的弹性容器,通过自动上边距把按钮推至容器底部,从而实现两列按钮的高度对齐。
修改后的代码
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> </head> <body> <div class="container"> <div class="row"> <!-- 左侧列设置垂直弹性布局 --> <div class="col mb-0 d-flex flex-column"> <h2>h2 text</h2> <h4>h4 text</h4> <h4>Another h4 text</h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> <!-- mt-auto自动填充上方空间,将按钮推至底部 --> <div class="text-center mt-auto"><button>Button 1</button></div> </div> <!-- 右侧列同样设置垂直弹性布局 --> <div class="col mb-0 d-flex flex-column"> <h2>Right Div</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> <!-- 按钮添加mt-auto和text-center,保持与左侧按钮对齐且居中 --> <button class="mt-auto text-center">Button 2</button> </div> </div> </div> </body> </html>
关键类说明
d-flex flex-column:把列容器转为垂直方向的弹性布局,让内部元素沿垂直轴排列。mt-auto:自动分配顶部外边距,利用弹性布局特性将元素推至容器底部,无论列内上方内容高度如何,都能保证按钮在底部对齐。
备选CSS方案(无法使用Bootstrap类时)
如果不能依赖Bootstrap类,可通过自定义CSS实现相同效果:
.col { display: flex; flex-direction: column; } .btn-bottom { margin-top: auto; text-align: center; }
给按钮或其容器添加btn-bottom类即可。
内容的提问来源于stack exchange,提问作者Nuwan Harshakumara Piyarathna
相关产品推荐
相关产品推荐

