skip to Main Content

I have multiple images of different sizes to display within one container. I want the images to all shrink the same percentage so that the widest one doesn’t exceed the width of the container. For example:

<div class="container">
    <img src="16x20.png" />
    <img src="16x40.png" />
    <img src="16x80.png" />
</div>

If the container is 80 pixels or wider, I want the images to all render at their original size.

If the container is 40 pixels wide, I would want the images to all be scaled down exactly 50% (that is, 8×10, 8×20, and 8×40). And so on.

I’ve tried a number of things including object-fit, max-width, transform: scale(); none of those seems to work. Thanks!

2

Answers


  1. From the way that you described it, I believe that you are looking for:

    .container img {
      width: 100%;
      object-fit: scale-down;
      max-width: 100%;
    }
    

    This will make the images responsive and fill the container for smaller sizes, but will not exceed 100% of their width for larger.

    Login or Signup to reply.
  2. I’ll make the assumption that you can’t alter the image’s code and add IDs or classes, so I would suggest using the :nth-of-type selector.

    .container img:nth-of-type(1) {
      width: 25%;
    }
    .container img:nth-of-type(2) {
      width: 50%;
    }
    .container img:nth-of-type(3) {
      width: 100%;
    }
    .container img {
      object-fit: scale-down;
      max-width: 100%;
    }
    

    With that, you can select each image and give it a percentage of the container size.
    See example to change container size: https://codepen.io/doncroy/pen/OJomBzM

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search