skip to Main Content

I have a div of dimensions 630x630px. Now I want to place an image inside this div. If image is larger than 630px (it’s width or height) I can simply use max-width and max-height and it will be fitted to 630px. But what if image is smaller than 630px? In that case I would like this image’s larger dimension to be stretched with constant aspect ratio to 630px. How can I do it?

2

Answers


  1. You can use the object-fit and object-position CSS properties on the image to achieve this. Your code should look like this:

    .container {
      width: 630px;
      height: 630px;
      position: relative;
    }
    
    .container img {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      max-width: 100%;
      max-height: 100%;
      object-fit: contain;
      object-position: center center;
    }
    
    Login or Signup to reply.
  2. I would avoid using position: absolute; when it’s unnecessary.
    object-fit does the trick by itself.

    .container {
      width: 630px;
      height: 630px;
      
      /* To visualize better the behavior of the image */
      border: 1px solid #333;
      margin-bottom: 1rem;
    }
    
    .container img {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
    <div class="container">
      <img src="https://placehold.co/1200x1000" alt="">
    </div>
    
    <div class="container">
      <img src="https://placehold.co/150x80" alt="">
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search