Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you vertically align multi-line text within a list?

Tags:

html

css

Example: jsfiddle.net/h5sE6/

css:

ul {
    float: left;
    margin-right:20px;
}
ul li {
    height: 3em;
    border: 1px solid #ff0000;
    width:200px;
}

html:

<ul>
    <li> Some text</li>
    <li>Some text<br />some more text</li>
    <li>some test text3</li>
    <li>even more text<br />and more</li>
</ul>
<ul>
    <li> Some text</li>
    <li>Some text<br />some more text</li>
    <li>some test text</li>
    <li>even more text<br />and more</li>
</ul>

This is trivial with vertically aligning text and making the height equal to the line-height if you have one line only but any more than that, things look really screwy.

like image 597
Brandon Minton Avatar asked Oct 10 '11 19:10

Brandon Minton


2 Answers

You can do it with a helper :before element and by adding a nested <span>:

ul li span {
    display: inline-block;  
    vertical-align: middle;     
}

ul li:before{
    content: '';
    display: inline-block;
    vertical-align: middle;
    height: 100%;       
}

Here's a demo of it in action.

This works because two inline-block elements will vertically align with each other. The :before rule creates an inline-block element that is the same height as its parent, which the variable height <span> can vertically align with.

For a complete explanation of how it works, see this answer about vertically aligning images.

like image 56
Pat Avatar answered Sep 27 '22 20:09

Pat


You can do this by adding a span to your markup and then using display:table etc in your css:

<ul>
    <li><span>Some text</span></li>
    <li><span>Some text<br />some more text</span></li>
    <li><span>some test text</span></li>
    <li><span>even more text<br />and more</span></li>
</ul>

CSS

ul {
    display: table;
    border-collapse: collapse;
    width: 100%;
}

ul li {
    height: 3em;
    border: 1px solid #ff0000;
    display: table-row;
}

ul li span{
    display:table-cell;
    vertical-align: middle;
}

Example: http://jsfiddle.net/jasongennaro/nePt6/

like image 29
Jason Gennaro Avatar answered Sep 27 '22 18:09

Jason Gennaro