CSS3 flex - 拉伸图像而不是居中?

时间:2017-02-10 10:37:32

标签: html css css3 flexbox

为什么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

1 个答案:

答案 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>