CSS3 flex - 拉伸图像,而不是集中它? [英] CSS3 flex - stretches the image instead of centering it?

查看:326
本文介绍了CSS3 flex - 拉伸图像,而不是集中它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么flex中心拉伸我的形象,而不是集中它?



css:

  .flex-center {
display:flex;
justify-content:center;
flex-direction:column;
text-align:center;
身高:100%;
宽度:100%;

HTML:

 < div style =height:400px; width:400px; background:#ccc> 
< div class =flex-center>
< / div>
< / div>

结果:



有什么想法吗?

jsfiddle

解决方案

$ c> flex-direction:column ,现在主轴是 Y ,横轴是X.因此,因为 align-items 沿着跨轴分发项目(并且默认值 align-items stretch )现在您想要使用 align-items:center 可以水平放置图片,并防止图片伸展。 $ b

  .flex-center {display:fle X; justify-content:center; flex-direction:column; align-items:center; text-align:center;身高:100% width:100%;}  

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

将图像的左右两边保证金设置为 auto



  .flex-center {display:flex; justify-content:center; flex-direction:column; text-align:center;身高:100% width:100%;} img {margin:0 auto;}  

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

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

解决方案

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>

这篇关于CSS3 flex - 拉伸图像,而不是集中它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆