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.
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.
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.
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 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.
This recipe can be found in it's original form on Stack Over Flow.