CSS force image resize and keep aspect ratio

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

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

\"\"

相关标签:
23条回答
  • 2020-11-22 10:58

    You can create a div like this:

    <div class="image" style="background-image:url('/to/your/image')"></div>
    

    And use this css to style it:

    height: 100%;
    width: 100%;
    background-position: center center;
    background-repeat: no-repeat;
    background-size: contain; // this can also be cover
    
    0 讨论(0)
  • 2020-11-22 10:59

    Very similar to some answers here, but in my case I had images that sometimes were taller, sometimes larger.

    This style worked like a charm to make sure that all images use all available space, keep the ratio and not cuts:

    .img {
       object-fit: contain;
       max-width: 100%;
       max-height: 100%;
       width: auto;
       height: auto;
    }
    
    0 讨论(0)
  • 2020-11-22 11:00

    There is no standard way to preserve aspect ratio for images with width, height and max-width specified together.

    So we are forced either to specify width and height to prevent page “jumps” during loading images, or to use max-width and not specify dimensions for images.

    Specifying just width (without height) typically makes not much sense, but you can try to override the height HTML-attribute by adding a rule like IMG {height: auto; } into your stylesheet.

    See also the related Firefox bug 392261.

    0 讨论(0)
  • 2020-11-22 11:01

    Here is a solution :

    img {
       width: 100%;
       height: auto;
       object-fit: cover;
    }
    

    This will make sure the image always covers the entire parent (scaling down and up) and keeps the same aspect ratio.

    0 讨论(0)
  • 2020-11-22 11:01

    I would suggest for a responsive approach the best practice would be using the Viewport units and min/max attributes as follows:

    img{
      display: block;
      width: 12vw;
      height:12vw;
      max-width:100%;
      min-width:100px;
      min-height:100px;
      object-fit:contain;
    }
    
    0 讨论(0)
提交回复
热议问题