How to scale an image with css to fill a div keeping aspect ratio?

后端 未结 6 1890
情深已故
情深已故 2021-02-13 15:10

I\'d like to fill a div with an img, keeping aspect ratio and stretching either width or height as much as required to fit in.

相关标签:
6条回答
  • 2021-02-13 15:30

    use background-size:cover

    div{
      background-image:url(http://placekitten.com.s3.amazonaws.com/homepage-samples/200/140.jpg);
      background-size:cover;
      }
    <div style="width:80px;height:80px;"></div>

    0 讨论(0)
  • 2021-02-13 15:33
    .thumb {
        max-width:100%;
        height:auto;
    }
    

    Or ( to allow scale up and down, which will look pixelated if you scale up, where the above will only scale to the max size of the image )

    .thumb {
        width:100%;
        height:auto;
    }
    

    Is what you are looking for.

    More info on responsive images:

    1. http://demosthenes.info/blog/586/CSS-Fluid-Image-Techniques-for-Responsive-Site-Design

    2. http://www.w3schools.com/css/css_rwd_images.asp

    0 讨论(0)
  • 2021-02-13 15:38

    the following did the trick:

        width:100%;
        height:100%;
        object-fit: cover;
        overflow: hidden;
    
    0 讨论(0)
  • 2021-02-13 15:43

    Using max-width, the image will be contained inside the div, there will be no overflow.

    If you use min-width instead, the shorter side will be exactly 100% of the div while the other side can be longer. To center the image, we can use translate and relative positioning.

    The following code works.

    div {
      overflow: hidden;
    } 
    .thumb {
      min-width: 100%;
      min-height: 100%;
      transform: translate(-50%, -50%);
      position: relative;
      left: 50%;
      top: 50%;
    }
    
    0 讨论(0)
  • 2021-02-13 15:46

    Not sure if anyone still looking at this post. I came across this while I was looking for a way to fit a image into a < div > without getting the unwanted white space around the image, because I was using hover & stick-out effect. I was inspired by Matt's solution. Instead of

    .thumb {
    max-width:100%;
    height:auto;}
    

    I added

    .thumb {
    max-width:100%;
    max-height:100%;
    height:auto;}
    

    Now my images fit in to the < div > perfectly without having those white space stick out with the image.

    0 讨论(0)
  • 2021-02-13 15:49

    To keep an image's aspect ratio, just specify one dimension:

    div {
        width: 80px;
        height: 80px;
        border: 2px solid red;
        overflow: hidden;
    }
    
    img {
        height: 100%;
    }
    

    This will produce the following effect:

    However, as you can see, the kitten is not central, but you can use Flex box to sort this out.

    div {
        width: 80px;
        height: 80px;
        border: 2px solid red;
        justify-content: center;
        display: flex;
        flex-direction: row;
    }
    
    img {
        flex: 1;
        height: 100%;
    }
    

    0 讨论(0)
提交回复
热议问题