Image stretching in flexbox in Safari

前端 未结 5 2034
别那么骄傲
别那么骄傲 2020-12-14 00:31

This is only an issue in Safari and looks like a Safari bug to me. Here is a fiddle with a simplified version of the issue.

When an image is in a nested flexbox elem

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-14 01:25

    It certainly appears to be a bug.

    The default setting for the align-items property is stretch. Most major browsers handle this sensibly, stretching the image within the confines of the container.

    For whatever reason, Safari stretches the image to its natural height, taking the container along for the ride.


    flex-direction: row

    To fix the problem, override the stretch default value with flex-start in the align-items property.

    .container {
      display: flex;
      flex-direction: column;
    }
    .container section:first-child {
      display: flex;
      align-items: flex-start; /* new */
      margin-bottom: 25px;
    }
    .container img {
      width: 125px;
      height: auto;
    }

    jsFiddle demo


    flex-direction: column

    Switching the direction of the flex container to column also fixes the problem. This works because align-items now applies to width and you've defined a width on the image.

    If you reverse the image dimensions from

    .container img {
       width: 125px;
       height: auto;
    }
    

    to

    .container img {
       width: auto;
       height: 125px;
    }
    

    ... you'll have the same problem in Safari as in flex-direction: row, and need align-items: flex-start for the correction.

    .container {
      display: flex;
      flex-direction: column;
    }
    
    .container section:first-child {
      display: flex;
      /* align-items: flex-start; */
      margin-bottom: 25px;
    }
    
    .container img {
      width: auto;
      height: 125px;
    }

    jsFiddle demo

提交回复
热议问题