CSS force image resize and keep aspect ratio

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

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

\"\"

23条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 10:55

    How about using a pseudo element for vertical alignment? This less code is for a carousel but i guess it works on every fixed size container. It will keep the aspect ratio and insert @gray-dark bars on top/bottom or left/write for the shortest dimension. In the meanwhile the image is centered horizontally by the text-align and vertically by the pseudo element.

        > li {
          float: left;
          overflow: hidden;
          background-color: @gray-dark;
          text-align: center;
    
          > a img,
          > img {
            display: inline-block;
            max-height: 100%;
            max-width: 100%;
            width: auto;
            height: auto;
            margin: auto;
            text-align: center;
          }
    
          // Add pseudo element for vertical alignment of inline (img)
          &:before {
            content: "";
            height: 100%;
            display: inline-block;
            vertical-align: middle;
          }
        }
    

提交回复
热议问题