【问题标题】:How to vertically center elements of body without centering navbar如何在不居中导航栏的情况下垂直居中主体元素
【发布时间】:2018-10-10 01:51:23
【问题描述】:

所以我有一个带有navbar 和一堆内容的页面。代码大纲如下:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="navbar">
<!-- Various navbar links here -->
</div>

<div class="container">
<!-- Some content here -->
</div>

我想要的是将container 置于body 的中心,但将navbar 保持在顶部。

上面的代码在中心对齐navbar 和container。如何在body 中垂直居中container 并防止navbar 居中?

【问题讨论】:

    标签: html twitter-bootstrap css flexbox


    【解决方案1】:

    你可以这样做:

    html, body {height: 100%} /* mandatory */
    body {margin: 0} /* mandatory */
    
    body {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
    
    .navbar {
      position: absolute;
      top: calc(50% - 150px); /* moved down by 50% of the screen height - half of the container's height - navbar's height */
      width: 1200px;
      max-width: 100%;
      height: 50px;
      background: Khaki;
    }
    
    .container {
      width: 1200px;
      max-width: 100%;
      height: 200px;
      background: Lavender;
    }
    <div class="navbar">
    <!-- Various navbar links here -->
    </div>
    
    <div class="container">
    <!-- Some content here -->
    </div>

    body 元素应该变成带有flex-direction: column的flex-container,这样它的items 垂直堆叠。因为你只想center .container div,你给.navbar 一个absolute position 并用top 将它移到它上面 property 和适当的 value,使用 CSS calc() function 计算。

    【讨论】:

      【解决方案2】:

      你可以给 .container 一个固定的宽度:

      .container {
      
      max-width: 860px;
      margin-right: auto;
      margin-left: auto;
      }
      

      【讨论】:

        【解决方案3】:

        您可以将 body 设为 flex 列容器,并将 margin 用于 .navbar 和 .container,而不是来自 flex 父级的 justify-content 和 align-items。

        需要基本代码:

        html,
        body {
          height: 100%;
          margin: 0;
        }
        
        body {
          display: flex;
          flex-direction: column;
        }
        
        .navbar {
          margin: 0 auto;
        }
        
        .container {
          margin: auto;
        }
        <div class="navbar">navbar
        </div>
        
        <div class="container">
          container
        </div>

        (min-)width 和 (min-)height 可以应用于您的盒子以满足您的需求。

        【讨论】:

          猜你喜欢
          • 2012-07-09
          • 1970-01-01
          • 1970-01-01
          • 2013-11-22
          • 2013-11-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-10
          相关资源
          最近更新 更多