2017-03-05 26 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>