Vertically align an image inside a div with responsive height

后端 未结 10 1683
遇见更好的自我
遇见更好的自我 2020-11-22 02:47

I have the following code which sets up a container which has a height that changes with the width when the browser is re-sized (to maintain a square aspect ratio).

10条回答
  •  再見小時候
    2020-11-22 03:36

    I came across this thread in search of a solution that:

    • uses 100% of the given image's width
    • keeps the image aspect ratio
    • keeps the image vertically aligned to the middle
    • works in browsers that do not fully support flex

    Testing some of the solutions posted above I didn't find one to meet all of this criteria, so I put together this simple one which might be useful for other people needing to do the same:

    .container {
      width: 30%;
      float: left;
      border: 1px solid turquoise;
      margin-right: 3px;
      margin-top: 3px;
    }
    
    .container:last-of-kind {
      margin-right: 0px;
    }
    
    .image-container {
      position: relative;
      overflow: hidden;
      padding-bottom: 70%;
      /* this is the desired aspect ratio */
      width: 100%;
    }
    
    .image-container img {
      position: absolute;
      /* the following 3 properties center the image on the vertical axis */
      top: 0;
      bottom: 0;
      margin: auto;
      /* uses image at 100% width (also meaning it's horizontally center) */
      width: 100%;
    }

    Working example on JSFiddle

提交回复
热议问题