Vertically center text that has no descenders?


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!

Problem courtesy of: boyers


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.

Solution courtesy of: boyers


line-height is actually given when we want to align the block elements in between along y-axis.

For example, i have a singled line text in w3schools and para height is 20px. The paragraph will be written in its own default way but if i use line-height equals the height of the paragraph then text in say W3schools will be aligned in the middle along y-axis. While if you want to horizontally align (x-axis align) your text then text-align:center is used for this purpose.

Remember, line-height do not totally depend on the height of its own element height. But it changes as follows.

  1. If you have a single line text, height is 20px then give line-height: 20px to vertically align the text or vertically middle of text.
  2. If you have a two line of text, height is 20px then give the line-height:10px and with the small padding-top to vertically align the text.

I hope this will lift you up. And i think you will not need to browse google more. If more you want explanation then i will give you jfiddle code. :)

Discussion courtesy of: Hassaan

This recipe can be found in it's original form on Stack Over Flow.