tailwindcss line-height、leading 未生效?如何垂直居中?

<nav class="w-full nav h-12">
    <div class="container mx-auto flex">
        <div class="w-24 leading-6 text-center h-12 hover:bg-black">首页</div>
        <p class="w-24 leading-6 text-center h-12 hover:bg-black">首页</p>
        <span class="w-24 leading-6 text-center h-12 hover:bg-black">首页</span>
    </div>
</nav>

这里的leading-x 均未生效,请问垂直居中如何写!!!

阅读 3.1k
3 个回答

因为 h-12 的实际值是 height: 3rem;,而你 leading-6 的实际值是 line-height:1.5rem 差了一半,自然没有垂直居中啊。
另外 leading-* 的最大值只有到 leading-10(也就是 line-height: 2.5rem),并没有 leading-12
image.png

所以说你想要垂直居中,可以这样设置原子类:

<nav class="nav h-12 w-full">
  <div class="container mx-auto flex">
    <div class="flex h-12 w-24 items-center justify-center hover:bg-black hover:text-white">首页</div>
    <p class="flex h-12 w-24 items-center justify-center hover:bg-black hover:text-white">首页</p>
    <span class="flex h-12 w-24 items-center justify-center hover:bg-black hover:text-white">首页</span>
  </div>
</nav>

image.png

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

<nav class="nav h-10 w-full">
  <div class="container mx-auto flex">
    <div class="h-10 w-24 text-center leading-10 hover:bg-black hover:text-white">首页</div>
    <p class="h-10 w-24 text-center leading-10 hover:bg-black hover:text-white">首页</p>
    <span class="h-10 w-24 text-center leading-10 hover:bg-black hover:text-white">首页</span>
  </div>
</nav>

image.png


当然你也可以自己设置一个 leading-12 的类出来然后去使用。

没有研究过tailwindcss

但是我引入了看一下,发现leading-*就是设置 line-height 你如果想要垂直剧中,容器的height等于line-height就可以了

我在线试了一下,观察了一下h-12是设置容器高度的,按道理 leading-12就可以居中,但是发现默认没有,

所以要么要自己定义,或者 如下图,就可以

1680076522161.png

本文参与了SegmentFault 思否面试闯关挑战赛,欢迎正在阅读的你也加入。

方法一:

确实是leading-12 这个类没有在tailwindcss 里面,需要额外定义

查看h-123rem 那么这个leading-12{line-height:3rem}

方法二:

<div class="w-24 leading-[3rem] text-center h-[3rem] hover:bg-black">首页</div>

以传值的方式给到固定的值如:leading-[3rem]h-[3rem]

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题