使用Tailwindcss在网格中垂直居中div

6tqwzwtp  于 2023-01-22  发布在  其他
关注(0)|答案(2)|浏览(270)

我试图在CSS网格中水平和垂直居中一个div。我使用TailwindCSS v3。使用mx-auto,我可以水平对齐内容,但是align-middle沿着flexbox没有显示任何结果。我附上下面的代码片段。

<div className="grid grid-cols-6 mb-2">
  <div className="col-span-1">
    <div className="flex align-middle">
      <ImLocation className="text-lg text-black mx-auto" />
    </div>
  </div>

  <div className="col-span-5">
    <p className="text-sm md:text-base text-black">
      Address Line 1, <br />
      Address Line 2, <br />
      Address Line 3
    </p>
  </div>
</div>

这里的问题是第一个inner-div(类col-span-1)的高度比另一个div小。我希望那个div与另一个div垂直居中对齐。ImLocation是我使用过的一个react图标。

dxpyg8gm

dxpyg8gm1#

使用items-centerjustify-center,如下所示:

<div className="grid grid-cols-6 mb-2">
    <div className="col-span-1">
        <div className="flex flex-row items-center justify-center">
            <ImLocation className="text-lg text-black mx-auto" />
        </div>
    </div>

    <div className="col-span-5">
        <p className="text-sm md:text-base text-black">
            Address Line 1, <br />
            Address Line 2, <br />
            Address Line 3
        </p>
    </div>
</div>
bf1o4zei

bf1o4zei2#

<div class="flex justify-center items-center h-full">
  <!-- Your content here -->
</div>

使用Tailwind CSS的flexjustify-centeritems-center类可以使元素在父容器中居中。“flex”类指示元素显示为一个灵活的容器,而“justify-center”和“items-center”类分别指示元素居中。上面的代码片段使div元素在父容器中水平和垂直居中。
为了让这段代码正常工作,父容器必须配置为相对于上面的div的位置。

完整代码:

<link href="https://cdn.jsdelivr.net/npm/tailwindcss/dist/tailwind.min.css" rel="stylesheet"/>
<div class="grid grid-cols-6 mb-2">
  <div class="col-span-1">
    <div class="flex justify-center items-center h-full">
      your content
    </div>
  </div>

  <div class="col-span-5">
    <p class="text-sm md:text-base text-black">
      Address Line 1, <br />
      Address Line 2, <br />
      Address Line 3
    </p>
  </div>
</div>

Explore the details on how to center an element using Tailwind CSS

相关问题