skip to Main Content

I have a container that contains random amount of images(1-3) and text.

If there is one image, the image needs to take the whole width, if there are two half the width etc

How can I implement such a thing?

Here is my code –

.images {
    display: flex;
}

.images img {
    max-height: 520px;
}
<div className="container">
    <div className="user-container">
        <div className="avatar">M</div>
        <div className="user-data">
            <div>Username</div>
            <div>Time</div>
        </div>
    </div>
    <div className="content">
   Some Random Text
    </div>
    <div className="images">
        <img src="https://picsum.photos/id/222/200/300">
        <img src="https://picsum.photos/id/231/200/300">
    </div>
</div>

2

Answers


  1. You have to tell the images in question to resize themselves evenly. For this you set flex-grow and flex-shrink both to 1 (you can use the shorthand flex: 1 1 for this). After that also tell the images to start filling the available place from a size of 0

    .images img {
      flex: 1 1;
      max-height: 512px;
      width: 0;
    }
    

    This will space out all your images, regardless of how many you have.

    If you do not specify the width: 0 the images will try to take their intrinsic width, resulting in overflowing.

    Login or Signup to reply.
  2. You can simply achieve this by using flex.

    Set the parent to display: flex, then set the same flex to the childs,
    the items will grow or shrink to fit the space available in its flex container.

    flexbox
    flex property

    .images {
        display: flex;
    }
    
    .images img {
        flex: 1
    }
    

    Example based on your code:

    https://codesandbox.io/s/gallant-fire-gjr1db?file=/style.css

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