2017-10-06 75 views
1

我不知道如何使用flexbox將<h1>正確標題放在頁面的中心。如何居中橫向和縱向標題(flexbox)?

這裏是一個鏈接: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:

回答

0

您需要嵌套您的彈性盒並將其方向更改爲列。我放在一起的例子使用Flexbox的,如果你想繼續使用,而不是一個位置,50%的黑客:

.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; 
 
}
<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>

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> 

希望有所幫助。