首页 > 解决方案 > Flexbox Hero 不会居中

问题描述

我不知道为什么 justify-self 不适用于我的 .hero-content。

我试图让我的 .hero-content 水平和垂直居中,它水平居中但垂直它仍然被推到顶部。不知道该怎么办。

.hero {
 height: 100vh;
 width: 100vw;
 background-image: url("../img/main.jpg");
 background-size: cover;
 color: #ffffff;
 display: flex;
 flex-direction: column;
}

header {
 display: flex;
 justify-content: space-between;
 align-items: center;
 padding: 25px 50px;
 opacity: 0;
 animation: fadeIn 1s .5s forwards;
}

.hero-content {
 display: flex;
 flex-direction: column;
 align-items: center;
 justify-content: center;
}
<section class="hero">
 <header>
   <a href="#" class="logotype">Mountain Travel</a>
   <nav>
     <ul class="top-nav__menu">
      <li class="top-nav__menu-item"><a href="#">Tours</a></li>
      <li class="top-nav__menu-item"><a href="#">About</a></li>
      <li class="top-nav__menu-item"><a href="#">Contact Us</a></li>
    </ul>
   </nav>
 </header>
 <div class="hero-content">
  <h2>Mountain Travel</h2>
  <h3 class="small-margin-top">Unmissable Adventure Tours Around the World</h3>
  <button class="cta">Contact Us Now</button>
 </div>
</section>

标签: htmlcssflexbox

解决方案


你需要flex-grow: 1在你的.hero-content. 在此处输入图像描述

演示(查看整页)

.hero {
 height: 100vh;
 width: 100vw;
 background-image: url("../img/main.jpg");
 background-size: cover;
 color: #ffffff;
 display: flex;
 flex-direction: column;
}

header {
 display: flex;
 justify-content: space-between;
 align-items: center;
 padding: 25px 50px;
 opacity: 1;
 animation: fadeIn 1s .5s forwards;
}

.hero-content {
 display: flex;
 flex-direction: column;
 align-items: center;
 justify-content: center;
 flex-grow: 1;
}

/************** 
** DEMO ONLY **
**************/

.hero-content h2 {
  margin-top: 0;
}

.hero-content {
  background-color: #eee;
}

.hero-content * {
  color: #333;
}
<section class="hero">
 <header>
   <a href="#" class="logotype">Mountain Travel</a>
   <nav>
     <ul class="top-nav__menu">
      <li class="top-nav__menu-item"><a href="#">Tours</a></li>
      <li class="top-nav__menu-item"><a href="#">About</a></li>
      <li class="top-nav__menu-item"><a href="#">Contact Us</a></li>
    </ul>
   </nav>
 </header>
 <div class="hero-content">
  <h2>Mountain Travel</h2>
  <h3 class="small-margin-top">Unmissable Adventure Tours Around the World</h3>
  <button class="cta">Contact Us Now</button>
 </div>
</section>


推荐阅读