Tailwind CSS中l(wèi)ine-height與leading屬性失效及垂直居中如何解決?

Tailwind CSS中l(wèi)ine-height與leading屬性失效及垂直居中如何解決?

Tailwind css 中 line-height 和 leading 屬性失效及文本垂直居中策略

在使用 Tailwind CSS 布局時(shí),常常遇到文本垂直居中難題。本文針對(duì) leading-x 屬性失效以及如何在高度為 12 單位的元素內(nèi)垂直居中文本提供解決方案。

問(wèn)題:開(kāi)發(fā)者使用 h-12 設(shè)置元素高度為 12 單位,并嘗試使用 leading-6 控制行高以實(shí)現(xiàn)垂直居中,但效果不佳。原因是 h-12 對(duì)應(yīng) height: 3rem,而 leading-6 對(duì)應(yīng) line-height: 1.5rem,兩者比例差異導(dǎo)致文本偏離中心。此外,leading-* 最大值為 leading-10 (即 line-height: 2.5rem),沒(méi)有 leading-12。

解決方案:

立即學(xué)習(xí)前端免費(fèi)學(xué)習(xí)筆記(深入)”;

方案一:flex 布局實(shí)現(xiàn)垂直居中

利用 Flex 布局的 items-center 和 justify-center 屬性,輕松實(shí)現(xiàn)文本垂直和水平居中。

<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">首頁(yè)</div>     <p class="flex h-12 w-24 items-center justify-center hover:bg-black hover:text-white">首頁(yè)</p>     首頁(yè)   </div> </nav>

此方案簡(jiǎn)潔高效,無(wú)需調(diào)整 leading 值。

方案二:調(diào)整元素高度并使用 leading-10

如果可以調(diào)整元素高度,將 h-12 改為 h-10,并使用 leading-10。 line-height 和 height 比例更接近,實(shí)現(xiàn)近似垂直居中。

<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">首頁(yè)</div>     <p class="h-10 w-24 text-center leading-10 hover:bg-black hover:text-white">首頁(yè)</p>     首頁(yè)   </div> </nav>

也可自定義 leading-12 類(lèi)滿足特殊需求。

選擇哪種方案取決于頁(yè)面設(shè)計(jì)和元素高度的靈活性。 Flex 布局通常是更推薦的方案,因?yàn)樗`活且易于維護(hù)。

以上就是T

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點(diǎn)贊13 分享
站長(zhǎng)的頭像-小浪學(xué)習(xí)網(wǎng)月度會(huì)員