3

Having trouble trying to align my final items in a grid layout using Tailwind (with React). Basically I want 3 items across and where there are not 3 items remaining, i.e 2 or 1, I want them centered .

I have tried some kind of col span but didn't work as intended.

To better illustrate what I am trying to do I have attached some diagrams

Current Layout:

display of current layout

Desired layout where 2 items left over :

Desired layout 1

Desired layout where 1 item left over :

desired layout 2

<div className="xl:grid grid-cols-3 gap-4">
 //cards .map(item) 
</div>
krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88
vornies
  • 105
  • 7

1 Answers1

4

You can consider using flex, flex-wrap, justify-center

7 items:

<div class="flex flex-wrap justify-center gap-2">
  <div class="h-40 w-60 bg-cyan-200"></div>
  <div class="h-40 w-60 bg-cyan-200"></div>
  <div class="h-40 w-60 bg-cyan-200"></div>
  <div class="h-40 w-60 bg-cyan-200"></div>
  <div class="h-40 w-60 bg-cyan-200"></div>
  <div class="h-40 w-60 bg-cyan-200"></div>
  <div class="h-40 w-60 bg-cyan-200"></div>
</div>

Output: enter image description here

8 items:

enter image description here

<div class="flex flex-wrap justify-center gap-2">
  <div class="h-40 w-60 bg-cyan-200"></div>
  <div class="h-40 w-60 bg-cyan-200"></div>
  <div class="h-40 w-60 bg-cyan-200"></div>
  <div class="h-40 w-60 bg-cyan-200"></div>
  <div class="h-40 w-60 bg-cyan-200"></div>
  <div class="h-40 w-60 bg-cyan-200"></div>
  <div class="h-40 w-60 bg-cyan-200"></div>
  <div class="h-40 w-60 bg-cyan-200"></div>
</div>

Play around using tailwind-css playground

krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88
  • 1
    My thoughts as well! If you with some calc and "arbitrary values" like `w-[calc(33.333%_-_4px)] aspect-square` after an exact `gap-[4px]` [you can even get](https://play.tailwindcss.com/Ds348MHpzF) the setup with square items. - A grid for the OP's situation will be very hard, because the hardest edge case is not really a _grid_ anymore. – Jeroen Mar 31 '23 at 05:56
  • 1
    @Jeroen, I agree with you , I wanted to keep it simple so didn't include `w-[calc(33.333%_-_4px)]`, that is a great and perfect approach for his problem. – krishnaacharyaa Mar 31 '23 at 05:58
  • redacted my comments as had an issue where i have 3 different images for the cards (repeated per name) but each image is actually a different size , having set an exact w to the image(rather than w-full) and then adding w-60 ,fixes my issue. Calc also worked however ran into issues with sizing of the cards where content is not the same – vornies Mar 31 '23 at 06:25