2016-11-16 46 views
5

我掙扎水平居中在我的容器一些內容:內容居中水平使用Flexbox的

https://jsfiddle.net/y56t31q9/6/

.container { 
 
    display: flex; 
 
    flex-direction: column; 
 
    width: 600px; 
 
    background-color: blue; 
 
    justify-content: center; 
 
    /* Not centering content horizontally? */ 
 
} 
 
.item { 
 
    max-width: 500px; 
 
    height: 100px; 
 
    background-color: yellow; 
 
    border: 2px solid red; 
 
}
<div class="container"> 
 
    <div class="item"></div> 
 
    <section class="item"></section> 
 
    <section class="item"></section> 
 
    <footer class="item"></footer> 
 
</div>

我還以爲證明內容將有完成了這個伎倆,但無濟於事。

任何幫助將不勝感激 謝謝!

+0

可能的重複:http://stackoverflow.com/q/32551291/3597276 –

回答

2

酒店justify-content:center對齊沿着彎曲方向彎曲項 - 使用align-items:center - 看演示如下:

.container { 
 
    display: flex; 
 
    flex-direction: column; 
 
    width: 600px; 
 
    background-color: blue; 
 
    justify-content: center; 
 
    align-items:center;/*NEW*/ 
 
} 
 
.item { 
 
    max-width: 500px; 
 
    width: 250px;/*NEW*/ 
 
    height: 100px; 
 
    background-color: yellow; 
 
    border: 2px solid red; 
 
}
<div class="container"> 
 
    <div class="item"></div> 
 
    <section class="item"></section> 
 
    <section class="item"></section> 
 
    <footer class="item"></footer> 
 
</div>

參見:Flexbox W3C spec

下面是適用於當flex-direction行的圖像:

image

一個。主軸對齊:對齊內容

b。十字軸對齊:對齊項

flex-direction行,主軸線是水平的,但是當它是,它是周圍的其他方式。

+1

非常感謝您的深入響應!意味着很多,歡呼聲 – Edwarric

1

添加align-items:center;

.container { 
    display: flex; 
    flex-direction: column; 
    width: 600px; 
    background-color: blue; 
    justify-content: center; 
    align-items:center; 
} 
1

刪除flex-direction:columnmax-width:500px。 給一些固定的寬度說100px,它會正常工作。如果您使用的是flex-direction:column,則使用align-items:center屬性來水平居中,如果它是row,則使用justify-center