如何防止flexbox水平拉伸我的图像?

时间:2017-06-08 03:56:44

标签: css image flexbox

我看到有关flexbox垂直拉伸图像的问题,并应用align-self:center修复它: Why does flexbox stretch my image?

但是,我的图像水平拉伸有问题: https://jsfiddle.net/qnnpxskk/

HTML:

<div class="wrapper">
  <div class="inner">
    <div class="row">
      <img src="https://www.wired.com/wp-content/uploads/2015/11/google-tensor-flow-logo-F.jpg">
    </div>
    <div class="row">
      <img src="https://www.wired.com/wp-content/uploads/2015/11/google-tensor-flow-logo-F.jpg">
    </div>
  </div>
</div>

CSS:

.wrapper{
  width: 600px;
  height: 900px;
  background: white;
}
.inner{
  display: flex;
  flex-direction: column;
}
.row{
  max-height: 100px;
  margin: 20px;
  display: flex;
  flex-direction: row;
  background: red;
}
.row img{
  max-height: 100%;
}

我尝试的所有东西似乎都无法让图像不被拉伸。我希望图像是父级的100%高度和宽度以保持原始的宽高比。

1 个答案:

答案 0 :(得分:2)

更新css部分

.row img{
  max-height: 100%;
  object-fit:contain; /* Add this You can change it as your need */
}
.inner{
  display: flex;
  flex-flow:column nowrap;
  justify-content:flex-start;
}
.wrapper{
  width: 100%; /*Add this*/
  height: 900px;
  background: white;
}

更新小提琴

<强> Update fiddle

&#13;
&#13;
.wrapper{
  width: 100%;
  height: 900px;
  background: white;
}
.inner{
  display: flex;
  flex-flow:column nowrap;
  justify-content:flex-start;
}
.row{
  max-height: 100px;
  margin: 20px;
  display: flex;
  flex-direction: row;
  background: red;
}
.row img{
  max-height: 100%;
  object-fit:contain;
}
&#13;
<div class="wrapper">
  <div class="inner">
    <div class="row">
      <img src="https://www.wired.com/wp-content/uploads/2015/11/google-tensor-flow-logo-F.jpg">
    </div>
    <div class="row">
      <img src="https://www.wired.com/wp-content/uploads/2015/11/google-tensor-flow-logo-F.jpg">
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

关于object-fit https://css-tricks.com/almanac/properties/o/object-fit/