在Bootstrap中垂直居中一组按钮
解决按钮在父div中垂直居中的问题
嘿,我来帮你搞定这个垂直居中的难题!你之前遇到的问题核心是:外层的.page用flex布局只是把整个table_cell块在页面里居中了,但按钮的父容器buttonBox并没有设置能让按钮垂直居中的规则,而且你用的margin: 0 auto和center-block都只是水平居中的方案,对垂直方向完全不起作用。
问题根源拆解
.page的display:flex作用在最外层,负责让table_cell在300px高的页面中居中,但这个规则不会自动传递到内部的buttonBox和按钮层级。.buttonBox作为Bootstrap的col-md-3,默认是display:block,而且没有设置高度——没有高度基准的话,垂直居中根本无从谈起。margin:0 auto和center-block都是针对水平方向的居中逻辑,和垂直居中没有关系。
具体解决方案
我们只需要给buttonBox添加flex布局规则,同时确保它有足够的高度作为居中基准,就能让按钮在父容器里完美垂直居中:
修改后的CSS代码
/*--CSS--*/ * { background-color: rgba(0, 0, 0, 0.1); } h1 { font-family: "Raleway", "sans-serif" !important; } h2 { font-family: "Raleway", "sans-serif" !important; } .page { height: 300px; display: flex; justify-content: center; align-items: center; } .table_cell { text-align: center; height: 100%; /* 继承.page的高度,传递给子元素 */ } /*--Page1--*/ .title {} #mainTitle { font-size: 8em; font-weight: 900 !important; letter-spacing: -3px; text-transform: uppercase; } #mainSub {} /*--Button--*/ .introButtons { margin: 0 auto !important; height: 100%; /* 继承table_cell的高度 */ } .buttonBox { display: flex; /* 开启flex布局 */ align-items: center; /* 实现垂直居中 */ justify-content: center; /* 实现水平居中 */ height: 100%; /* 继承introButtons的高度,给垂直居中提供基准 */ }
调整后的HTML代码(仅需移除多余的center-block类)
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> <div id="firstPage" class="page col-md-12"> <div class="table_cell col-md-8"> <div class="introButtons col-md-8"> <div class="buttonBox col-md-3"> <a href="#secondPage" class="btn">Who Are We?</a> </div> <div class="buttonBox col-md-3"> <a href="#thirdPage" class="btn">Our Projects</a> </div> <div class="buttonBox col-md-3"> <a href="#fourthPage" class="btn">Our Team</a> </div> <div class="buttonBox col-md-3"> <a href="#fifthPage" class="btn">Contact Us</a> </div> </div> </div> </div>
为什么这样调整能解决问题?
- 给
table_cell和introButtons添加height:100%,让它们继承.page的300px高度,这样buttonBox就能拿到明确的高度作为垂直居中的基准。 - 给
buttonBox开启display:flex,并通过align-items:center控制垂直居中、justify-content:center控制水平居中,按钮会自动在容器内居中,不需要再依赖center-block或margin:auto。
这样修改后,你的按钮就能在各自的父div里实现完美的垂直居中啦!
内容的提问来源于stack exchange,提问作者RePotato
相关产品推荐
相关产品推荐

