CSS3 flex - stretches the image instead of centering it?

﹥>﹥吖頭↗ 提交于 2019-12-23 19:16:03

问题


Why does flex center stretch my image instead of centering it?

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>

Result:

Any ideas?

jsfiddle


回答1:


You have set flex-direction: column and now main axis is Y and cross axis is X. So because align-items distribute items along cross-axis (and default value of align-items is stretch) now you want to use align-items: center to position your image horizontally and prevent image to stretch.

.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>

Another option is to set left and right margin of image to 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>


来源:https://stackoverflow.com/questions/42157249/css3-flex-stretches-the-image-instead-of-centering-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!