如何水平和垂直标题(flexbox)居中?

时间:2017-10-06 20:27:27

标签: html css

我不知道如何使用flexbox将<h1>准确地放在页面的中心位置。

这是一个链接:https://jsbin.com/movevezesi/edit?html,css,output

期望效果:https://tutorialzine.com/media/2016/06/landing-page-hero.jpg

HTML:

<div class="wrap">
<header class="header">
  <a class="logo" href="#">logo</a>

  <ul class="nav">
    <li><a href="#">Features</a></li>
    <li><a href="#">Pricing</a></li>
    <li><a href="#">Sign In</a></li>
    <li><a href="#">Free Trial</a></li>
  </ul>
   </header>
    <div class="hero">
      <h1>how to center horizontally and vertically this text ???</h1>
      <h2>any</h2>
      <h3>ideas???</h3>
    </div>
 </div>

的CSS:

2 个答案:

答案 0 :(得分:0)

你可以使用下一堂课。它将水平和垂直居中于元素。

.centerElement{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

<div class="hero centerElement">
  <h1>how to center horizontally and vertically this text ???</h1>
  <h2>any</h2>
  <h3>ideas???</h3>
</div>

希望它有所帮助。

答案 1 :(得分:0)

您希望嵌套弹性框并将其方向更改为列。如果你想继续使用它而不是50%黑客的位置,我把使用flexbox的例子放在一起:

&#13;
&#13;
.wrap {
  display: flex;
  
  /* 
     flex-direction: column keeps the nav and 
     hero in vertical alignment 
  */
  flex-direction: column; 
  border: 1px solid red;
  height: 500px;
}

.hero {
  display: flex;
  
  /*
     again, using flex-direction:column to keep
     the nested headers in vertical alignment
  */
  flex-direction: column;
  
  /* 
     flex-grow tells .hero to grow along the main
     flex axis of its parent. in this case we set
     wrap to flex-direction:column, so .hero stretches
     vertically
  */
  flex-grow: 1;
  
  /*
     justify-content sets the children's layout
     along the parent's main axis. in this case
     the headers will group up in the vertical middle
     of .hero
  */
  justify-content: center;
  
  /*
    align-items sets the children's layout perpendicular
    to the parent's main axis. so in this case they'll bunch up
    along the horizontal center
  */
  align-items: center;
  
  
  border: 1px solid red;
  
}

.hero > * {
  border: 1px solid black;
  
  /*
     without this text-align, the headers would 
     be centered horizontally, but the text inside those 
     headers would still be left-aligned
  */
  text-align: center;
}
&#13;
<div class="wrap">
  <header class="header">
    <a class="logo" href="#">logo</a>

    <ul class="nav">
      <li><a href="#">Features</a></li>
      <li><a href="#">Pricing</a></li>
      <li><a href="#">Sign In</a></li>
      <li><a href="#">Free Trial</a></li>
    </ul>
  </header>
  <div class="hero">
    <h1>how to center horizontally and vertically this text ???</h1>
    <h2>any</h2>
    <h3>ideas???</h3>
  </div>
</div>
&#13;
&#13;
&#13;