search

Home  >  Q&A  >  body text

How to center the last row of items in a grid using Tailwind CSS?

<p>I'm having trouble trying to use Tailwind (using React) to align my final project in a grid layout. Basically I want 3 items and if there are no 3 items left i.e. 2 or 1, I want them to be centered. </p> <p>I tried some sort of col span but it didn't work as expected. </p> <p>To better illustrate what I'm trying to do, I've attached some diagrams</p> <p>Current layout: </p> <p>Desired layout with 2 items remaining: </p> <p>Desired layout with 1 item remaining: </p> <pre class="brush:html;toolbar:false;"><div className="xl:grid grid-cols-3 gap-4"> //cards .map(item) </div> </pre></p>
P粉311563823P粉311563823511 days ago517

reply all(1)I'll reply

  • P粉187677012

    P粉1876770122023-08-29 10:26:21

    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:

    8 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 class="h-40 w-60 bg-cyan-200"></div>
    </div>

    Usetailwind-css Playground

    reply
    0
  • Cancelreply