Vertically align an image inside a div with responsive height

后端 未结 10 1653
遇见更好的自我
遇见更好的自我 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:41

    You can center an image, both horizontally and vertically, using margin: auto and absolute positioning. Also:

    1. It is possible to ditch extra markup by using pseudo elements.
    2. It is possible to display the middle portion of LARGE images by using negative left, top, right and bottom values.

    .responsive-container {
      margin: 1em auto;
      min-width: 200px;       /* cap container min width */
      max-width: 500px;       /* cap container max width */
      position: relative;     
      overflow: hidden;       /* crop if image is larger than container */
      background-color: #CCC; 
    }
    .responsive-container:before {
      content: "";            /* using pseudo element for 1:1 ratio */
      display: block;
      padding-top: 100%;
    }
    .responsive-container img {
      position: absolute;
      top: -999px;            /* use sufficiently large number */
      bottom: -999px;
      left: -999px;
      right: -999px;
      margin: auto;           /* center horizontally and vertically */
    }

    Note: images are center-cropped on <400px screen width.
    Open full page demo and resize browser.

提交回复
热议问题