Scaling Images Proportionally in CSS with Max-width

后端 未结 8 1585
余生分开走
余生分开走 2021-01-31 13:39

Right now, I\'m using max-width to scale images to fit. However, they don\'t scale proportionally. Is there a way to cause this to happen? I\'m open to Javascript/jQuery.

<
8条回答
  •  南旧
    南旧 (楼主)
    2021-01-31 14:13

    I had to do this with the following requirements:

    1. Page must not get reflown when images load. The image sizes are known on the server side and calculations can be made.
    2. Images must scale proportionally
    3. Images must not be wider than the containing element
    4. Images must not be scaled up, only down when necessary
    5. Must use an img element and not a background to make sure the images also print properly
    6. No JavaScript!

    The closest I came up with is this terrible contraption. It requires three elements and two inline styles, but as far as I know this is the best way to scale images proportionally. All the height: auto; suggestions here negate the point of specifying the image dimensions on the server side and cause the content to jump around while loading.

    .image {
      position: relative;
    }
    
    .image img {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }
    
    
    

    https://jsfiddle.net/Lqg1fgry/6/ - The "Hello" is there so you can see if the content after the image jumps around.

提交回复
热议问题