垂直居中没有下降的文本? [英] Vertically center text that has no descenders?

查看:30
本文介绍了垂直居中没有下降的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一行全部大写的文本(例如使用 text-transform: uppercase).我想在 div 中垂直居中此文本.我不需要担心多行文本.

Suppose I have a single line of text that is in all caps (e.g. with text-transform: uppercase). I want to center this text vertically in a div. I don't need to worry about multi-line text.

有几种方法可以在 CSS 中垂直居中(例如检查 this).不幸的是,所有这些方法都考虑了descenders,并且我的文本没有任何下降符,所以它没有完全居中.基本上,我想将文本的一部分从基线到大写高度居中.

There are several ways to center things vertically in CSS (e.g. check this out). Unfortunately, all these methods take descenders into account, and my text doesn't have any descenders so it isn't centered perfectly. Basically, I want to center the portion of the text from the baseline to the cap height.

有没有办法垂直居中一行大写文本?现在我正在使用 position: relative 并手动调整它直到它居中(例如使用 top: 2px),但这显然不是一个强大的解决方案(它是非常依赖于浏览器呈现文本的方式、可用的字体等).谢谢!

Is there any way to vertically center a line of capitalized text? Right now I'm using position: relative and manually tweaking it until it is centered (e.g. with top: 2px), but this is clearly not a robust solution (it is very dependent on the way the browser renders text, what fonts are available, etc.). Thanks!

推荐答案

经过一些测试,我似乎对文本如何垂直居中是错误的.事实证明,大多数浏览器完全按照我的意愿行事——它们不考虑下行.

After some testing, it seems I was wrong about how text is vertically centered. It turns out that most browsers do exactly what I want—they don't take descenders into account.

对于那些不清楚我在问什么的人:descender"是文本中低于基线的部分.例如,小写字符g"和y"具有低于基线的部分.我想垂直居中没有这些字符的文本(在我的例子中,只有像X"这样的大写字符).

For those who were unclear about what I was asking: The "descender" is the part of text that goes below the baseline. For example, the lowercase characters "g" and "y" have parts that go below the baseline. I wanted to vertically center text that does not have characters like these (in my case, only uppercase characters like "X").

Here 是一个 jsfiddle,它展示了我的发现(它设置了 line-heightdiv 的高度).请注意,X"正确居中,这使得g"溢出 div.但这对我来说没问题,因为文本都是大写的.

Here is a jsfiddle that demonstrates what I found (which sets line-height to the height of the div). Notice that the "X" is centered properly, which makes the "g" overflow outside the div. But that's okay for me, because the text is all caps.

这篇关于垂直居中没有下降的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆