2016-06-28 113 views
0

如何垂直居中放置此Bootstrap容器div?我想要它,所以我查看它在页面上垂直居中的页面,黑色在我的div上下。如何垂直居中Bootstrap容器?

演示: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; 
} 

回答

1

首先,你必须在容器的所有父元素设置为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; 
} 

jsFiddle

或者,试试这个CSS表方法,它似乎是工作好,并且不影响电网引导。请注意,添加两个额外的div作为包装。

html, body { 
    height: 100%; 
} 
body { 
    margin: 0; 
    background: black; 
} 
.container1 { 
    display: table; 
    width: 100%; 
    height: 100%; 
} 
.container2 { 
    display: table-cell; 
    vertical-align: middle; 
} 

jsFiddle