lau*_*kok 3 html css css3 flexbox
为什么flex中心会拉伸我的图像而不是居中?
CSS:
.flex-centre {
display: flex;
justify-content: center;
flex-direction: column;
text-align: center;
height: 100%;
width: 100%;
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
结果:
有任何想法吗?
您已设置flex-direction: column,现在主轴为Y,横轴为X.因此align-items,现在您希望使用水平定位图像并防止图像拉伸,因此沿着横轴(默认值为align-itemsis stretch)分配项目align-items: center.
.flex-centre {
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
text-align: center;
height: 100%;
width: 100%;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
另一种选择是将margin图像的左右两侧设置为auto
.flex-centre {
display: flex;
justify-content: center;
flex-direction: column;
text-align: center;
height: 100%;
width: 100%;
}
img {
margin: 0 auto;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)