2016-06-28 68 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