display:flex & image sizing/centering

前端 未结 1 1500
有刺的猬
有刺的猬 2021-01-24 09:22

I am using display: flex; to center an image and max-width / max-height to size it. There are several of these images - some wide, some ta

相关标签:
1条回答
  • 2021-01-24 10:01

    It seems flexbox do not scale down images (that have an intrinsic aspect ratio) correctly in browsers at the moment, at least! (For more info, you can look at this discussion)

    So I have two solutions for this:

    1. Set flex-basis for the img

    .image_block {
      padding: 20px;
      height: 140px;
      background: #eee;
      display: flex;
    }
    .image_block img {
      margin: auto;
      max-width: 170px;
      max-height: 90px;
      flex-basis: 170px;
    }
    <div class="image_block">
      <img src="http://www.paulruocco.com/jobjacket/assets/uploads/company_uploads/image_070816132332577fe19495484.png" />
    </div>

    1. Wrap the img with a div tag.

    .image_block {
      padding: 20px;
      height: 140px;
      background: #eee;
      display: flex;
    }
    .image_block div {
      margin: auto;
    }
    .image_block div img {
      max-width: 170px;
      max-height: 90px;
    }
    <div class="image_block">
      <div><img src="http://www.paulruocco.com/jobjacket/assets/uploads/company_uploads/image_070816132332577fe19495484.png" /></div>
    </div>

    Also I would suggest you use flexbox techniques instead of using margin: auto:

    .image_block {
      padding: 20px;
      height: 140px;
      background: #eee;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .image_block img {
      max-width: 170px;
      max-height: 90px;
      flex-basis: 170px;
    }
    <div class="image_block">
      <img src="http://www.paulruocco.com/jobjacket/assets/uploads/company_uploads/image_070816132332577fe19495484.png" />
    </div>

    Let me know your feedback on this. Thanks!

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