Fill a div with an image respecting aspect ratio

后端 未结 4 1826
悲哀的现实
悲哀的现实 2020-12-04 03:51

Is it possible to fill a div with an image such that at least one image dimension is 100% and the other dimension is either wider or equal size as the div, whilst r

4条回答
  •  时光说笑
    2020-12-04 03:59

    Here is the solution without using background images and with HTML and CSS only: http://codepen.io/anon/pen/JGGObQ

    (change overflow to visible in the .container1 rule to see the full pictures. The numbers in them are their original size in pixels.)

    It uses position: absolute on the images, and depending on the format (two classes, as suggested by yourself) a top or left of 50% that moves the position reference into the (horizontal or vertical) center, and a transform : translate setting that moves the position reference point of the image back from that center by 50% of their own size, which results in centering:

    .container1 {
      position: relative;
      float: left;
      margin-right: 50px;
      width: 400px;
      height: 400px;
      border-radius: 50%;
      overflow: hidden;
      border: 1px solid red;
    }
    img.landscape {
      position: absolute;
      width: auto;
      height: 100%;
      transform: translate(-50%, 0);
      left: 50%;
    }
    img.portrait {
      position: absolute;
      width: 100%;
      height: auto;
      transform: translate(0, -50%);
      top: 50%;
    }

提交回复
热议问题