display:flex & image sizing/centering

前端 未结 1 1521
有刺的猬
有刺的猬 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;
    }

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

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

    Let me know your feedback on this. Thanks!

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