Problem
How do I get the “x” in the middle of the span to be vertically aligned?
.foo {
height: 50px;
border: solid black 1px;
display: inline-block;
vertical-align: middle;
}
<span class="foo">
x
</span>
Asked by mike
Solution #1
Instead of height, use line-height:50px; That ought to suffice 😉
Answered by Sindre Sorhus
Solution #2
Be cautious that the line-height strategy fails if the span contains a long sentence that breaks the line due to a lack of space. You’d have two lines with a gap the height of the N pixels supplied in the attribute in this scenario.
When I needed to show an image with vertically centered text on its right side in a responsive web application, I stuck with it. As a starting point, I use Eric Nickus and Felipe Tadeo’s method.
If you want to achieve the following goals:
and this:
Answered by lluisaznar
Solution #3
If you require numerous lines, this is the simplest way to achieve it. Wrap your span’d content in a new span and use line-height to set its height. Resetting the inner span’s line-height is the key to numerous lines.
<span class="textvalignmiddle"><span>YOUR TEXT HERE</span></span>
.textvalignmiddle {
line-height: /*set height*/;
}
.textvalignmiddle > span {
display: inline-block;
vertical-align: middle;
line-height: 1em; /*set line height back to normal*/
}
DEMO
Of fact, the outside span could be a div or something else entirely.
Answered by Hashbrown
Solution #4
The flexbox way:
.foo {
display: flex;
align-items: center;
justify-content: center;
height: 50px;
}
Answered by Chris Clower
Solution #5
Because I needed this for links, I wrapped the span in an a-tag and a div, then centered the span tag.
HTML
<div>
<a class="tester" href="#">
<span>Home</span>
</a>
</div>
CSS
.tester{
display: inline-block;
width: 9em;
height: 3em;
text-align: center;
}
.tester>span{
position: relative;
top: 25%;
}
Answered by Jason
Post is based on https://stackoverflow.com/questions/732337/how-do-i-vertically-align-something-inside-a-span-tag