Home > Software engineering >  Align 4 images in a row without overflowing CSS
Align 4 images in a row without overflowing CSS

Time:11-13

I'm trying to create a row of images and I have a container that uses half the width of the page and each image takes up a quarter of that half like this:

<div key={index} >
                       
  {/* Images */}
  <div >
      <img src={row.image} alt="Product"></img>

      <div >
          <img src="../images/placeholder.svg" alt="Product" ></img>
          <img src="../images/placeholder.svg" alt="Product" ></img>
          <img src="../images/placeholder.svg" alt="Product" ></img>
          <img src="../images/placeholder.svg" alt="Product" ></img>
      </div>
  </div>
</div>

As you can see I have one large image above and 4 smaller images which I would like to align underneath. This currently gives this effect: enter image description here

As you can see the bottom images overflow into the right-hand column. I don't want to overflow hidden or add a scrollbar but instead, I would like the images to be even sizes across this space, with a small gap inbetween. Like this example: enter image description here

As you can see there's no overflow and the 4 images are even sizes and spaced underneath the image. This is the effect I would like to replicate. I'm currently using Tailwind CSS but a regular CSS explanation would work fine if anyone is unfamiliar with Tailwind.

From my understanding, there's nothing directly wrong with the code as each image does take up a 1/4, however, when I apply some margins to space them apart the images can shrink because they must maintain their 1/4 width. This then pushes the images to one side. I would like any suggestions for a clear approach to achieve the design in image two.

CodePudding user response:

You can use flexbox for this. Make sure the parent div have the properties:

display: inline-flex;
justify-content: space-evenly;

Then I believe your children/images should have this property to define its width:

flex-basis: 20%;

Take a look at this website for a quick flexbox reference. https://css-tricks.com/snippets/css/a-guide-to-flexbox/

CodePudding user response:

It's generally easier to put the images in their own column element, let the column handle the gaps, and then let the image fill the container. I'd do it this way:

<div key={index} >
  {/* Images */}
  <div >
      <img src={row.image} alt="Product"></img>

      <div >
          <div >  
            <img src="../images/placeholder.svg" alt="Product"></img>
          </div>
          <div >
            <img src="../images/placeholder.svg" alt="Product"></img>
          </div>
          <div >
            <img src="../images/placeholder.svg" alt="Product"></img>
          </div>
          <div >
            <img src="../images/placeholder.svg" alt="Product"></img>
          </div>
      </div>
  </div>
</div>

Example playground link: https://play.tailwindcss.com/JQlTDnaFdd

  • Related