CSS force image resize and keep aspect ratio

前端 未结 23 1251
野趣味
野趣味 2020-11-22 10:04

I am working with images, and I ran across a problem with aspect ratios.

\"\"

23条回答
  •  鱼传尺愫
    2020-11-22 10:49

    To maintain a responsive image while still enforcing the image to have a certain aspect ratio you can do the following:

    HTML:

    image

    And SCSS:

    .ratio2-1 {
      overflow: hidden;
      position: relative;
    
      &:before {
        content: '';
        display: block;
        padding-top: 50%; // ratio 2:1
      }
    
      img {
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
      }
    }
    

    This can be used to enforce a certain aspect ratio, regardless of the size of the image that authors upload.

    Thanks to @Kseso at http://codepen.io/Kseso/pen/bfdhg. Check this URL for more ratios and a working example.

提交回复
热议问题