【问题标题】:Positionning with flexbox使用 flexbox 定位
【发布时间】:2017-07-25 11:11:04
【问题描述】:

我想使用 Flexbox 实现这个结果:

  • 红色的divcontainer
  • 绿色的div 是一个navbar 菜单,应该在顶部水平居中。
  • 然后页面的标题应该在图像显示时居中。

PS : 红色 div 的高度为 100vh,宽度为 100%。

使用此代码的结果在container 的中心显示绿色 div 和标题。

.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>

【问题讨论】:

    标签: html css twitter-bootstrap flexbox


    【解决方案1】:

    您可以引入一个新元素将内容包裹在中间,将其设置为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>

    【讨论】:

      【解决方案2】:

      headeralign-items: center 上设置flex-direction: column 用于水平居中。然后只需使用边距将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>

      【讨论】:

        猜你喜欢
        • 2020-02-24
        • 1970-01-01
        • 2023-03-30
        • 2020-06-28
        • 2017-12-17
        • 2022-11-17
        • 2019-05-18
        • 2018-02-08
        • 2017-03-09
        相关资源
        最近更新 更多