CSS force image resize and keep aspect ratio

前端 未结 23 1268
野趣味
野趣味 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

    The solutions below will allow scaling up and scaling down of the image, depending on the parent box width.

    All images have a parent container with a fixed width for demonstration purposes only. In production, this will be the width of the parent box.

    Best Practice (2018):

    This solution tells the browser to render the image with max available width and adjust the height as a percentage of that width.

    .parent {
      width: 100px;
    }
    
    img {
      display: block;
      width: 100%;
      height: auto;
    }

    This image is originally 400x400 pixels, but should get resized by the CSS:

    Fancier Solution:

    With the fancier solution, you'll be able to crop the image regardless of its size and add a background color to compensate for the cropping.

    .parent {
      width: 100px;
    }
    
    .container {
      display: block;
      width: 100%;
      height: auto;
      position: relative;
      overflow: hidden;
      padding: 34.37% 0 0 0; /* 34.37% = 100 / (w / h) = 100 / (640 / 220) */
    }
    
    .container img {
      display: block;
      max-width: 100%;
      max-height: 100%;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
    }

    This image is originally 640x220, but should get resized by the CSS:

    For the line specifying padding, you need to calculate the aspect ratio of the image, for example:

    640px (w) = 100%
    220px (h) = ?
    
    640/220 = 2.909
    100/2.909 = 34.37%
    

    So, top padding = 34.37%.

提交回复
热议问题