如何垂直居中这个 Bootstrap 容器 div?我想要它,所以我查看页面时它在我的 div 上方和下方的页面上垂直居中。
演示: https://jsfiddle.net/yunr225g/
HTML:
<div class="container">
<div class="row">
<div class="col-md-6 text-center">
<img src="http://placehold.it/250x250">
<button type="submit">Stay</button>
</div>
<div class="col-md-6 text-center">
<img src="http://placehold.it/250x250">
<button type="submit">Leave</button>
</div>
</div>
</div>
CSS:
body {
margin: 10px;
background:black;
}
button {
display:block;
text-align:center;
margin:0 auto;
margin:60px auto;
background:black;
border:2px solid #ffca00;
padding:30px;
width:250px;
color:#ffca00;
text-transform:uppercase;
}
最佳答案
首先,您必须将容器的所有父元素设置为height:100%
,或者直接使用height:100vh
。然后,使用 position
+ transform
技巧使其垂直居中。
这在大屏幕上效果很好,您可能需要通过媒体查询和小屏幕断点来调整它。
html, body {
height: 100%;
}
body {
margin: 0;
background: black;
}
.container {
position: relative;
top: 50%;
transform: translateY(-50%);
border: 1px solid red;
}
或者,尝试使用这种 CSS 表格方法,它似乎运行良好,并且不会影响 Bootstrap 网格。请注意,添加了两个额外的 div 作为包装器。
html, body {
height: 100%;
}
body {
margin: 0;
background: black;
}
.container1 {
display: table;
width: 100%;
height: 100%;
}
.container2 {
display: table-cell;
vertical-align: middle;
}
关于html - 如何垂直居中 Bootstrap 容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38081820/