簡體   English   中英

當容器小於行高時,如何垂直對齊文本?

[英]How to vertically align text when container is smaller than the line height?

我有一個小div(26 x 26px),並且想要添加一個字體大小為30px的單個字符。 我希望此文本在框中垂直對齊。 但是,即使設置了line-heightvertical-align屬性,我也無法將文本抬高到容器的中心。

有沒有簡單的方法可以做到這一點,還是我需要訴諸於嵌套的div和transforms?

 .zoom button { width: 26px; height: 26px; border: 1px solid #bcbcbc; padding: 0; font-size: 30px; /** these don't see to help **/ line-height: 26px; vertical-align: middle; } 
 <div class="zoom"> <button>-</button> <button>+</button> </div> 

問題在於減號。 您可以考慮使用偽元素來修復它,在該元素中將應用vertical-align並調整其line-height

請注意, line-height:0將完成按鈕元素的工作,因為默認情況下內容在中心對齊。 我還添加了vertical-align: top以避免按鈕之間的未對齊

 .zoom button { width: 26px; height: 26px; border: 1px solid #bcbcbc; padding: 0; font-size: 30px; line-height: 0; vertical-align: top; } .zoom button:first-child::before { content: ""; vertical-align: middle; line-height: 20px; /*any value between 17px and 24px will do the job (don't ask me why ...)*/ } 
 <div class="zoom"> <button>-</button> <button>+</button> </div> 

在我看來,最簡單的方法是將文本包裝在一個inline-block框中,從中設置font-sizeline-height大約這些字體的三分之二)(對於這些字符),按鈕將自行居中。

偽選項也適用。 看看@Temani Afif答案

 .zoom button { width: 26px; height: 26px; border: 1px solid #bcbcbc; padding: 0; } .zoom.bis button { width: 46px; height: 46px; text-align: center; /* just for info */ } .zoom.ter button span { font-size: 40px; } .zoom button span { font-size: 30px; line-height: 0.66em;/* or 20px .. a third */ } .zoom { margin: 1em; float: left; } 
 <div class="zoom"> <button><span>-</span></button> <button><span>+</span></button> </div> <div class="zoom bis"> <button><span>-</span></button> <button><span>+</span></button> </div> <div class="zoom bis ter"> <button><span>-</span></button> <button><span>+</span></button> </div> 

它必須對'+'字符進行處理,所有其他字符都可以正確顯示。 嘗試:

 .zoom button { width: 26px; height: 26px; border: 1px solid #bcbcbc; padding: 0; font-size: 30px; line-height: 30px; } .plus, .minus { position: relative; top: -4px; } 
 <div class="zoom"> <button><span class="minus">-</span></button> <button><span class="plus">+</span></button> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM