Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering elements in a grid layout in Tailwind

Tags:

tailwind-css

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?

like image 501
Matt Avatar asked Jul 23 '26 00:07

Matt


1 Answers

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.

like image 121
Leonardo Dagnino Avatar answered Jul 25 '26 08:07

Leonardo Dagnino