max-width of img inside flexbox doesn't preserve aspect ratio

前端 未结 1 985
灰色年华
灰色年华 2021-01-02 00:44

I\'m trying to use flex to simply vertically center an img inside div, but it is working differently in each browser.

相关标签:
1条回答
  • 2021-01-02 01:14

    How to fix IE and Firefox

    The following changes should result in the same result across Chrome, Firefox and IE:

    • Add flex: 0 0 auto; to .flex-item img. This fixes IE
    • Add object-fit: scale-down; to .flex-item img. This fixes Firefox

    .flex-container {
      display: -webkit-box;
      display: -moz-box;
      display: -ms-flexbox;
      display: -webkit-flex;
      display: flex;
      -webkit-flex-flow: row wrap;
      -ms-flex-flow: row wrap;
      flex-flow: row wrap;
      justify-content: flex-start;
    }
    .flex-item {
      height: 222px;
      width: 200px;
      border: 1px solid lightgray;
      padding: 5px;
      margin: 5px;
    }
    .flex-item img {
      flex: 0 0 auto;
      max-width: 100%;
      max-height: 100%;
      align-self: center;
      -webkit-align-self: center;
      margin: auto;
      object-fit: scale-down;
    }
    .item-image {
      border: 1px solid lightgray;
      display: -webkit-box;
      display: -moz-box;
      display: -ms-flexbox;
      display: -webkit-flex;
      display: flex;
      width: 190px;
      height: 120px;
    }
    <div class="flex-container">
      <div class="flex-item">
        <div class="item-image">
          <img src="http://www.joshuacasper.com/contents/uploads/joshua-casper-samples-free.jpg">
        </div>
      </div>
      <div class="flex-item">
        <div class="item-image">
          <img src="https://c1.staticflickr.com/9/8264/8700922582_d7b50280b4_z.jpg">
        </div>
      </div>
      <div class="flex-item">
        <div class="item-image">
          <img src="http://www.pinaldave.com/bimg/ilovesamples.jpg">
        </div>
      </div>
      <div class="flex-item">
        <div class="item-image">
          <img src="http://appslova.com/wp-content/uploads/2014/11/Android-.png">
        </div>
      </div>
    </div>

    JS Fiddle: https://jsfiddle.net/7yyf3nob/

    Why does this happen?

    Unfortunately I can't explain why the result between the browsers is so different other than it would appear that the natural resizing properties of an img are lost when using the flexbox model in IE and Firefox. flexbox is still a relatively new model and the vendors are still refining their implementations.

    0 讨论(0)
提交回复
热议问题