Variations on this question have been asked many times. Vertical centering with CSS is a challenge.
I have a particular scenario, dealing with a list displayed horizontally. The markup is like this:
<ul id='ul1' class='c'>
<li><a href='javascript:void(0)'>Fribble Fromme</a></li>
<li><a href='javascript:void(0)'>Fobble</a></li>
<li><a href='javascript:void(0)'>Foo Fickle Pickle</a></li>
</ul>
The style is like this:
ul.c {
height:52px;
text-align:center;
}
ul li a {
float:left;
text-decoration:none;
border: 1px solid Maroon;
padding:2px 12px;
background:#FFEF8A;
line-height:1em;
width:100px;
}
ul li a:hover {
background: #CCC;
}
ul li {
height:52px;
display:inline-block;
}
The resulting list looks like this:
But I want all the boxes to be the same height, and I want the text to be vertically centered in each box. I can set the box-height by adding a height
style for the A elements. The result looks like this:
...which is close to what I want, but the vertical-centering isn't happening.
I can set line-height
for the text, as suggested in this post, to do the vertical centering. I can even pick different values of line-height
for different A elements, if I know which of the elements will get multiple lines of text. But I don't know which ones will require multiple lines.
How can I get it to center when some of the A elements have text that wraps?
You could use display:table
, etc. along with vertical-align:middle
ul.c {
text-align:center;
display:table;
}
ul li {
float:left;
}
ul li a {
text-decoration:none;
border: 1px solid Maroon;
padding:2px 12px;
background:#FFEF8A;
width:100px;
height:52px;
display:table-cell;
vertical-align:middle;
}
ul li a:hover {
background: #CCC;
}
Example: http://jsfiddle.net/kf52n/2/