无法在Flexbox中垂直对齐项目

时间:2020-08-02 04:16:31

标签: css flexbox

我正在学习使用flexbox,但无法在类.headercontent内垂直对齐内容。它似乎尊重justify-content之类的所有其他事物,但忽略了align-content。我搜索并发现了this线程,这似乎表明应明确设置父级的高度。我通过设置flex-basisflex-grow以及min-height来设置高度。但是仍然由div包含h1停留在header的顶部。我希望该绿色div位于header的垂直中心。我在做什么错了?

html {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-size: 100%;
            line-height: 1.2em;
          }
          body {
            display: flex;
            flex-direction: column;
            justify-content: flex-start;
            align-items: stretch;
            height: 100vh;
            background-color: #cdc9c1;
          }
          header {
            background-color: #a99879;
            flex-basis: 10%;
            flex-grow: 1;
            min-height: 20px;
          }
          main {
            background-color: #5b431a;
            flex-basis: 80%;
            flex-grow: 8;
          }
          footer {
            background-color: #77613c;
            flex-basis: 10%;
            flex-grow: 1;
          }
          .headercontent {
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
            background-color: green;
            min-height: 20px;
          }
          .navstyle {
            list-style-type: none;
          }
<html>
      <head>
      </head>
      <body>
        <header>
          <div class="headercontent">
            <h1>This is the header</h1>
        </div>
        </header>
        <nav>
          <ul>
            <li>section1</li>
            <li>section2</li>
            <li>section3</li>
          </ul>
        </nav>
        <main>
          <p> this is the main body</p>
        </main>
        <footer>
          <p> this is the footer </p>
        </footer>
      </body>
    </html>

这是我的作品https://codepen.io/knows_not_much/pen/rNxXoOM的可待因链接

1 个答案:

答案 0 :(得分:1)

我希望绿色div位于标题的垂直中心。什么 我做错了吗?

您的header元素占据body高度的10%。您的.headercontent不会占据header的整个定义高度。因此,它将位于顶部。为了解决这个问题,您可以将header元素分配为flex容器,也就是在其中分配align-items: center; justify-content: center属性的地方

header {
    background-color: #a99879;
    flex-basis: 10%;
    flex-grow: 1;
    display: flex; /* add these */
    align-items: center; /* add these */
    justify-content: center; /* add these */
}

如果必须让绿色背景占用空间,请随后根据需要将width: 100%分配给.headercontent