align-items:center和navigation

时间:2017-11-02 21:33:03

标签: html css flexbox

我正在使用flexbox垂直和水平居中我的标题中的文字全屏。但是我也希望在那里有导航和一些标志,但当然这两个都在中间。

如何解决此问题,以便我可以将导航和徽标放在顶部,使用flexbox将文本放在中间?

这是我的代码:

HTML:

<header>
    <nav>
        <a href="#">Home</a>
        <a href="#">About</a>
        <a href="#">Contact</a>
    </nav>
    <h2>Template</h2>
    <h1>Welcome to my page</h1>
    <a href="#">Learn More</a>
</header>

CSS:

header {
    height: 100vh;
    background: url(img/showcase.jpg) center center;
    background-size: cover;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    text-align: center;
}

提前致谢。

1 个答案:

答案 0 :(得分:0)

您可以使用margin-bottom:auto使代码更简洁,更短:

* {
  /* reset */
  margin: 0;
}

header {
  height: 100vh;
  background: linear-gradient(to top, rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5)), url(http://lorempixel.com/640/480/technics/1) center center;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  text-align: center;
}

nav,
header>a {
  margin: 0 0 auto;
  /* will adjust from bottom: 
  result is the group <h2>,<h1> and <a> having margin:auto on top and bottom 
  putting them together in the middle of the space of header unused by <nav>*/
}


/* for the fun and demo of margin behavior */

header:hover {
  flex-flow: column-reverse;
}
<header>
  <nav>
    <a href="#">Home</a>
    <a href="#">About</a>
    <a href="#">Contact</a>
  </nav>
  <h2>Template</h2>
  <h1>Welcome to my page</h1>
  <a href="#">Learn More</a>
</header>

否则,您可以从justify-content:space-between;开始,并将每个元素上的margin重置为中心。

* {
  /* reset */
  margin: 0;
}

header {
  height: 100vh;
  background: linear-gradient(to top, rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5)), url(http://lorempixel.com/640/480/technics/1) center center;
  background-size: cover;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-direction: column;
  text-align: center;
}

h2 {
  margin: auto auto 0;
}

h1 {
  margin: 0;
}

a {
  margin: 0 auto auto
}


/* for the fun and demo of margin behavior */

header:hover {
  flex-flow: column-reverse;
}
<header>
  <nav>
    <a href="#">Home</a>
    <a href="#">About</a>
    <a href="#">Contact</a>
  </nav>
  <h2>Template</h2>
  <h1>Welcome to my page</h1>
  <a href="#">Learn More</a>
</header>
两个片段看起来都很相似,但事实并非如此。悬停header以查看margin效果*(流量反转显示)*。

您也可以在nav中设置position:absolute,但这不再是灵活的...