Tailwind CSS 中 line-height 和 leading 失效及垂直居中技巧详解
在使用 Tailwind CSS 布局时,文本垂直居中常常是个挑战。本文通过一个实际案例,分析 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> 首页 </div> </nav>
然而,leading-6 并不能使文本垂直居中。
原因分析及解决方案:
问题根源在于 h-12 (高度 3rem) 与 leading-6 (行高 1.5rem) 的数值不匹配。行高小于高度的一半,导致文本无法垂直居中。此外,leading-* 的最大值为 leading-10 (行高 2.5rem),因此 leading-12 无效。
解决方法如下:
方法一:Flex 布局 + items-center 和 justify-center
利用 Flex 布局,结合 items-center (垂直居中) 和 justify-center (水平居中),轻松实现垂直居中:
<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> 首页 </div> </nav>
方法二:调整高度并使用 leading-10
如果可以调整导航栏高度,将 h-12 改为 h-10 (高度 2.5rem),并使用 leading-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> 首页 </div> </nav>
如有特殊需求,可自定义 leading-12 等类。 选择哪种方法取决于具体设计和对导航栏高度的要求。
以上就是Tailwind CSS中:line-height和leading失效以及如何实现文本垂直居中?的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号