
Tailwind CSS 中 line-height 和 leading 属性失效及文本垂直居中策略
在使用 Tailwind CSS 布局时,常常遇到文本垂直居中难题。本文针对 leading-x 属性失效以及如何在高度为 12 单位的元素内垂直居中文本提供解决方案。
问题:开发者使用 h-12 设置元素高度为 12 单位,并尝试使用 leading-6 控制行高以实现垂直居中,但效果不佳。原因是 h-12 对应 height: 3rem,而 leading-6 对应 line-height: 1.5rem,两者比例差异导致文本偏离中心。此外,leading-* 最大值为 leading-10 (即 line-height: 2.5rem),没有 leading-12。
解决方案:
立即学习“前端免费学习笔记(深入)”;
方案一:Flex 布局实现垂直居中
利用 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 值。
方案二:调整元素高度并使用 leading-10
如果可以调整元素高度,将 h-12 改为 h-10,并使用 leading-10。 line-height 和 height 比例更接近,实现近似垂直居中。
<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 类满足特殊需求。
选择哪种方案取决于页面设计和元素高度的灵活性。 Flex 布局通常是更推荐的方案,因为它更灵活且易于维护。
以上就是Tailwind CSS中line-height与leading属性失效及垂直居中如何解决?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号