在 Tailwind 的网格布局中居中元素

Centering elements in a grid layout in Tailwind

我正在努力获得以 Tailwind 为中心的网格布局。这是一个例子

    <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>

这是它的样子:

当然我可以添加 col-start-2 然后它会居中,但网格来自动态布局,我不知道是否有更多元素出现在同一行上。我试过 justify-center、justify-self-center、mx-auto,也尝试过 no-float,但没有任何效果。

有没有人有什么想法?

你可以这样做:

      <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>

您可能想要specify the repeat(auto-fit, 16.666666%) as part of your theme.

您可能还需要考虑当项目超过三个时您究竟想要发生什么 - 如果您需要第五个也是最后一个元素也居中,那么 flexbox 可能会更好。