2017-03-05 66 views
1

我想用Flexbox的實現這一結果:Positionning與Flexbox的

  • 紅色divcontainer
  • 綠色div是一個navbar菜單,應該在頂部水平居中。
  • 然後頁面的標題應該居中顯示圖像。

PS:紅色div的高度爲100vh,寬度爲100%。

enter image description here

使用該代碼同時顯示綠色的div和標題在container中心的結果。

.header { 
 
    height: 100vh; 
 
    display: flex; 
 
    flex-direction: column; 
 
    align-items: center; 
 
    justify-content: center; 
 
}
<div class="container-fluid"> 
 
    <div class="row"> 
 
    <div class="col-md-12 header"> 
 
     <div class="menu"> 
 
     <!-- navbar items --> 
 
     </div> 
 
     <h1>TITLE</h1> 
 
     <h2>Subtitle</h2> 
 
    </div> 
 
    </div> 
 
</div>

回答

2

您可以引入新的元素來包裝中間的內容,其設置爲flex-grow: 1,使其消耗所有從父遺留下來的可用空間,則居中內容的那個元素。

.header { 
 
    height: 100vh; 
 
    display: flex; 
 
    flex-direction: column; 
 
    align-items: center; 
 
} 
 
.header header { 
 
    flex-grow: 1; 
 
    display: flex; 
 
    flex-direction: column; 
 
    justify-content: center; 
 
} 
 
.header .menu { 
 
    border: 1px solid green; 
 
    margin-top: 1em; 
 
    width: 80%; 
 
    text-align: center; 
 
    padding: 1em; 
 
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> 
 
<div class="container-fluid"> 
 
    <div class="row"> 
 
    <div class="col-md-12 header"> 
 
     <div class="menu"> 
 
     header menu 
 
     </div> 
 
     <header> 
 
     <h1>TITLE</h1> 
 
     <h2>Subtitle</h2> 
 
     </header> 
 
    </div> 
 
    </div> 
 
</div>

1

設置flex-direction: columnheaderalign-items: center的水平居中。然後僅使用邊距垂直居中對齊h1h2。需要注意的是.menu將空間header因此H1和H2將在剩下的空間的中央,否則,你需要使用position: absolute

div.header { 
 
    display: flex; 
 
    flex-direction: column; 
 
    min-height: 100vh; 
 
    border: 2px solid red; 
 
    padding-top: 10px; 
 
    align-items: center; 
 
} 
 
div.menu { 
 
    border: 2px solid green; 
 
    height: 50px; 
 
    width: 50%; 
 
} 
 
.header h1 { 
 
    margin-bottom: 0; 
 
    margin-top: auto; 
 
} 
 
.header h2 { 
 
    margin-bottom: auto; 
 
    margin-top: 0; 
 
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/> 
 

 
<div class="container-fluid"> 
 
    <div class="row"> 
 
    <div class="col-md-12 header"> 
 
     <div class="menu"> 
 
     <!-- navbar items --> 
 
     </div> 
 
     <h1>TITLE</h1> 
 
     <h2>Subtitle</h2> 
 
    </div> 
 
    </div> 
 
</div>