skip to Main Content

I need to be able to make an image fill the entire container (the container’s width/height set with % or vh/vw), not necessarily keeping the image’s original aspect ratio, but with no overflow or unused space.

I have tried:

.container{
     width: 80%; /* for example */
     height: 30%;
}

.item{
     width:  100%;
     height: 100%;
     object-fit: cover;
}
     

but this doesn’t seem to work.

I know this can be done with JS, but I would prefer to do it in a cleaner way.

2

Answers


  1. Yes, you can do it.

    Will be like this. Without keeping image aspect ratio.

    example

    img {
      border: 0;
      vertical-align: top;
    }
    .container{
      width: 500px; 
      height: 250px;
      padding: 20px;
      background: blue;
      position: relative;
    }
    
    .item{
      width:  calc(100% - 40px);
      height: calc(100% - 40px);
      object-fit: fill;
      position: absolute;
      top: 20px;
      left: 20px;
     }
    

    Check it on codepen https://codepen.io/EkaterinaLabutina/pen/eYwaZgy

    Paddings were added on purpose.

    Login or Signup to reply.
  2. It looks like you’re on the right track with the object-fit: cover approach.
    You can try this

        .container {
      width: 80%; /* Responsive width */
      height: 30vh; /* Responsive height */
      overflow: hidden; /* Ensures no overflow from image */
    }
    
    .item {
      width: 100%;
      height: 100%;
      object-fit: none; /* Disables aspect ratio */
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search