I read many, many.... many tips on how to vertically align stuff inside elements. I couldn't find one that exactly did what I wanted.
To simplify, I have a div container and a span inside with a text, like this:
<html>
<body>
<div class="container">
<span>My Text</span>
</div>
</body>
</html>
I just wanted that my text be vertically aligned in the span. Here is the basic CSS I was using to try to align it.
.container {
margin: 20px 0;
height: 200px;
line-height: 200px;
text-align: center;
}
.container span {
color: white;
font-size: 200px;
font-weight: 900;
line-height: 200px;
vertical-align: middle; /* no effect */
}
Here is what it looks like with the inspector:
Notice that the top of the uppercase letters hit the top of the span, but the bottom of the letters, especially others than the
y
are far from the bottom of the span
. That gets even worse with monospace
font-family (which is the one I really want).
Weirdly enough, the top of the letters now don't touch the top of the span (?!)
I tried to manipulate the text inside the span using
position: relative
and changing the top
and bottom
, and I also tried to use the transform: translateX()
function, all to no avail.
So you may wonder why the hell that small space is important. Well, when I apply clip-path to my span, the polygon of 0 50% is not in the center of the text, in fact, because of the huge area on the bottom, it clips my text to almost 100% of the height of the letters, like this:
Yeah yeah, I know I can clip it to around 30% of the Y axis and be around 50% of the text, but 1) this will change depending on the font-family and 2) what the hell? What's up with that?
I haven't tried using flexbox
as I wasn't accepting that pure CSS couldn't do something simple like that. But maybe I'm missing something. Has anyone seen this?
I'm guessing the font "definition" has that huge space on the bottom reserved for some weird character, so the Roman letters are positioned on the top of the space and the bottom area is wasted?
EDIT (Answer to justinw):
my code in jsfiddle that you pasted on the commented shows up wrong both in FF and Chromium:
as for the second link, with flex in jsfiddle, the font size is too small, so I increased to check it and it shows wrong in FF
But it is correct in Chromium like that:
But even in Chromium, it fails with
font-family: monospace;
I have no idea why :(
EDIT (answer to Kenny):
As with the answer to justinw. It fails in FF:
It works in Chromium:
But fails in Chromium if the font-family is monospace:
EDIT (answer to Dexterians):
I added a gray background in the span for visualization purposes.
I pasted the screenshot from jsfiddle below, in FF. vertical-align
has no effect. And it fails:
In Chromium indeed vertical-align affects the positioning and it works (even a little better than the trials with flex as the bottom part of the "y" letter is inside the span box:
But even in Chromium it fails if the font-family is monospace: