
tailwind css 中的 line-height 未生效?解决垂直居中难题
使用 tailwind css 时,你可能会遇到 line-height 无法正常工作的情况,导致垂直居中无法正确实现。以下问题和解答将帮助你理解原因并解决此问题:
问题:
<pre><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></pre>
这里的 leading-6 均未生效,垂直居中如何实现?
解答:
此问题的根源在于 h-12 的实际值是 height: 3rem;,而 leading-6 的实际值是 line-height:1.5rem,两者差了一半,导致无法垂直居中。
另外,leading-* 的最大值只有到 leading-10(即 line-height: 2.5rem),没有 leading-12。
因此,想要垂直居中,可以这样设置原子类:
<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>或者,如果可以的话,缩小高度值为 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>当然,你也可以自己定义一个 leading-12 类并使用它。
以上就是Tailwind CSS 中的 line-height 为什么失效了?如何垂直居中元素?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号