3

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?

Matt
  • 3,206
  • 4
  • 24
  • 26
  • 1
    Read this for a thorough understanding of grid: https://stackoverflow.com/a/45599428/9920079 – Hackinet Mar 05 '22 at 03:14
  • 1
    Thank you @Hackinet, very useful. I don't think it actually covered what I was looking for, which specifically was centering one of the grid items. It was more about centering the content within the grid, rather than having a grid with for example 3 columns and centering when there are just 2 elements within it. But still very interesting, thank you! – Matt Mar 05 '22 at 19:33

1 Answers1

4

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.

Leonardo Dagnino
  • 2,914
  • 7
  • 28