【问题标题】:How to prevent flexbox stretching my image horizontally?如何防止 flexbox 水平拉伸我的图像?
【发布时间】:2017-11-09 14:47:44
【问题描述】:

我看到这个关于 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% 高度和保持原始纵横比的宽度。

【问题讨论】:

    标签: css image flexbox


    【解决方案1】:

    更新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

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

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

    【讨论】:

    猜你喜欢
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-04
    • 1970-01-01
    • 2017-06-04
    • 2012-01-30
    • 2015-03-13
    相关资源
    最近更新 更多