为什么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>
结果:
有什么想法吗?
答案 0 :(得分:6)
您已设置align-items
,现在主轴为 Y ,横轴为X.因此,align-items
沿着交叉轴分配项目(默认值为{{ 1}}是stretch
)现在您想使用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>