Matt
Matt

Reputation: 3716

Centering elements in a grid layout in Tailwind

I'm struggling to get a grid layout centered in Tailwind. Here's an example

<div class="grid grid-cols-6 p-24 justify-center bg-slate-500">
    <div class="w-full p-8 col-span-2 justify-center justify-self-center mx-auto bg-slate-900 text-white text-center text-lg">
        2 cols, should be centered
    </div>
</div>

And here's what that looks like:

enter image description here

Of course I could add col-start-2 and then it would be centered, but the grid is coming from a dynamic layout and I don't know whether there are more elements coming on the same row or not. I've tried justify-center, justify-self-center, mx-auto, also played around with no-float but nothing works.

Does anyone have any ideas?

Upvotes: 7

Views: 37446

Answers (3)

Zeeshan Ali
Zeeshan Ali

Reputation: 19

Use tailwind

<div class="grid grid-cols-6 p-24 bg-slate-500 place-items-center">
</div>

that should do the work

Upvotes: 1

Leonardo Dagnino
Leonardo Dagnino

Reputation: 3225

You can do something like this:

<div class="grid grid-cols-[repeat(auto-fit,_16.666666%)] m-auto p-24 justify-center bg-slate-500">
    <div class="w-full p-8 col-span-2 justify-center justify-self-center mx-auto bg-slate-900 text-white text-center text-lg">
        2 cols, should be centered
    </div>
</div>

You may want to specify the repeat(auto-fit, 16.666666%) as part of your theme.

You also may want to consider what exactly you want to happen when there are more than three items - if you need a fifth and last element to also be centered, then maybe a flexbox would serve you better.

Upvotes: 12

ranga durai
ranga durai

Reputation: 1

<div class="grid grid-cols-6 p-24 bg-slate-500">
  <!-- Empty columns for spacing -->
  <div class="col-span-2"></div>
  
  <!-- Centered 2-column section -->
  <div class="col-span-2 flex justify-center">
    <div class="w-full p-8 bg-slate-900 text-white text-center text-lg">
      2 cols, centered
    </div>
  </div>

  <!-- Empty columns for spacing -->
  <div class="col-span-2"></div>
</div>

Upvotes: 0

Related Questions