2017-02-10 20 views
3

爲什麼flex中心伸展我的形象,而不是集中它?CSS3 flex - 拉伸圖像而不是居中?

CSS:

.flex-centre { 
     display: flex; 
     justify-content: center; 
     flex-direction: column; 
     text-align: center; 
     height: 100%; 
     width: 100%; 
} 

HTML:

<div style="height: 400px; width: 400px; background: #ccc"> 
    <div class="flex-centre"> 
     <img class="img-responsive" src="http://placekitten.com/g/200/200" alt=""> 
    </div> 
</div> 

結果:

enter image description here

任何想法?

jsfiddle

回答

6

您已設置flex-direction: column現在主軸線是Ÿ和交叉軸是X.那麼因爲align-items分佈沿交叉軸項目(和默認值的align-itemsstretch),現在要使用align-items: center水平放置圖像並防止圖像拉伸。

.flex-centre { 
 
    display: flex; 
 
    justify-content: center; 
 
    flex-direction: column; 
 
    align-items: center; 
 
    text-align: center; 
 
    height: 100%; 
 
    width: 100%; 
 
}
<div style="height: 400px; width: 400px; background: #ccc"> 
 
    <div class="flex-centre"> 
 
    <img class="img-responsive" src="http://placekitten.com/g/200/200" alt=""> 
 
    </div> 
 
</div>

另一種選擇是圖像的左右margin設置爲auto

.flex-centre { 
 
    display: flex; 
 
    justify-content: center; 
 
    flex-direction: column; 
 
    text-align: center; 
 
    height: 100%; 
 
    width: 100%; 
 
} 
 
img { 
 
    margin: 0 auto; 
 
}
<div style="height: 400px; width: 400px; background: #ccc"> 
 
    <div class="flex-centre"> 
 
    <img class="img-responsive" src="http://placekitten.com/g/200/200" alt=""> 
 
    </div> 
 
</div>