首页 > 文章列表 > Tailwind CSS 中的 line-height 为什么失效了?如何垂直居中元素?

Tailwind CSS 中的 line-height 为什么失效了?如何垂直居中元素?

144 2024-12-02

Tailwind CSS 中的 line-height 为什么失效了?如何垂直居中元素?

tailwind css 中的 line-height 未生效?解决垂直居中难题

使用 tailwind css 时,你可能会遇到 line-height 无法正常工作的情况,导致垂直居中无法正确实现。以下问题和解答将帮助你理解原因并解决此问题:

问题:

<pre><nav class="w-full nav h-12">

&lt;div class=&quot;container mx-auto flex&quot;&gt;
    &lt;div class=&quot;w-24 leading-6 text-center h-12 hover:bg-black&quot;&gt;首页&lt;/div&gt;
    &lt;p class=&quot;w-24 leading-6 text-center h-12 hover:bg-black&quot;&gt;首页&lt;/p&gt;
    &lt;span class=&quot;w-24 leading-6 text-center h-12 hover:bg-black&quot;&gt;首页&lt;/span&gt;
&lt;/div&gt;

</nav></pre>

这里的 leading-6 均未生效,垂直居中如何实现?

解答:

此问题的根源在于 h-12 的实际值是 height: 3rem;,而 leading-6 的实际值是 line-height:1.5rem,两者差了一半,导致无法垂直居中。

另外,leading-* 的最大值只有到 leading-10(即 line-height: 2.5rem),没有 leading-12。

因此,想要垂直居中,可以这样设置原子类:

&lt;nav class=&quot;nav h-12 w-full&quot;&gt;
  &lt;div class=&quot;container mx-auto flex&quot;&gt;
    &lt;div class=&quot;flex h-12 w-24 items-center justify-center hover:bg-black hover:text-white&quot;&gt;首页&lt;/div&gt;
    &lt;p class=&quot;flex h-12 w-24 items-center justify-center hover:bg-black hover:text-white&quot;&gt;首页&lt;/p&gt;
    &lt;span class=&quot;flex h-12 w-24 items-center justify-center hover:bg-black hover:text-white&quot;&gt;首页&lt;/span&gt;
  &lt;/div&gt;
&lt;/nav&gt;

或者,如果可以的话,缩小高度值为 h-10 也可以:

&lt;nav class=&quot;nav h-10 w-full&quot;&gt;
  &lt;div class=&quot;container mx-auto flex&quot;&gt;
    &lt;div class=&quot;h-10 w-24 text-center leading-10 hover:bg-black hover:text-white&quot;&gt;首页&lt;/div&gt;
    &lt;p class=&quot;h-10 w-24 text-center leading-10 hover:bg-black hover:text-white&quot;&gt;首页&lt;/p&gt;
    &lt;span class=&quot;h-10 w-24 text-center leading-10 hover:bg-black hover:text-white&quot;&gt;首页&lt;/span&gt;
  &lt;/div&gt;
&lt;/nav&gt;

当然,你也可以自己定义一个 leading-12 类并使用它。

来源:1731362538