[英]vertically center element when height is smaller than container, but make height 100% when container height is smaller
[英]How to vertically align text when container is smaller than the line height?
我有一个小div(26 x 26px),并且想要添加一个字体大小为30px的单个字符。 我希望此文本在框中垂直对齐。 但是,即使设置了line-height
和vertical-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-size
和line-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.