如何使用Bootstrap让按钮在对应列中垂直居中显示
让Bootstrap列中的按钮垂直居中的解决方案
嘿,作为Bootstrap新手能写出这样的布局已经很不错啦!要把中间列的按钮调整到垂直居中位置,其实用flex布局就能轻松搞定,分两种情况给你说:
如果你用的是Bootstrap 4或更高版本
Bootstrap已经内置了flex工具类,直接用这些类就能实现,不用写额外CSS。只需要修改中间按钮所在的<section>标签,把它变成flex容器,同时设置垂直和水平居中:
修改后的中间section代码示例:
<section class="col-sm-2 d-flex align-items-center justify-content-center"> <button type="button" class="btn btn-default" id="data1">Process1</button> </section>
d-flex:把元素转为flex容器align-items:center:让容器内的子元素(也就是按钮)垂直居中justify-content:center:让按钮水平居中(保持你原来的text-center效果)
替换两行中间section的代码后,完整的HTML如下:
<div class="container"> <div class="row"> <section class="col-sm-5"> <div class="form-group"> <label for="project-name">Enter Data:</label> <textarea class="form-control" rows="3" id="textarea1" name="input1"></textarea> <div class="error" id="javaerror"></div> </div> </section> <section class="col-sm-2 d-flex align-items-center justify-content-center"> <button type="button" class="btn btn-default" id="data1">Process1</button> </section> <section class="col-sm-5"> <div> <label for="project-name">Result</label> <textarea class="form-control" rows="3" id="result1" name="resultdata"></textarea> </div> </section> </div> <div class="row"> <section class="col-sm-5"> <div class="form-group"> <label for="project-name">Enter Data:</label> <textarea class="form-control" rows="3" id="textarea2" name="input2"></textarea> <div class="error" id="openerror"></div> </div> </section> <section class="col-sm-2 d-flex align-items-center justify-content-center"> <button type="button" class="btn btn-default" id="data2">Process2 </button> </section> <section class="col-sm-5"> <div> <label for="project-name">Result</label> <textarea class="form-control" rows="3" id="result2" name="resultDataNew"></textarea> </div> </section> </div> </div>
如果你用的是Bootstrap 3
Bootstrap 3没有内置flex工具类,需要自定义一点CSS。先在你的样式表中添加:
/* 让行内的列高度一致 */ .row { display: flex; align-items: stretch; } /* 让中间列的内容垂直水平居中 */ .vcenter-col { display: flex; align-items: center; justify-content: center; }
然后修改中间的section标签,添加自定义类:
<section class="col-sm-2 vcenter-col"> <button type="button" class="btn btn-default" id="data1">Process1</button> </section>
这样左右列会被拉伸到同一高度,中间列的按钮就能完美居中啦~
原来你用的.vcenter类没生效,是因为没有给它设置足够的高度和正确的布局方式,flex布局是现在实现垂直居中最简洁的方案,兼容性也没问题,放心用吧!
内容的提问来源于stack exchange,提问作者Phoenix
相关产品推荐
相关产品推荐

