Search code examples
cssvertical-alignmentcss-tables

Centering content vertically in list which is displayed as table rows


I am creating vertical page navigation. I know exact height (300px) and that there will be 5 items (all of them may be of different sizes, but none of them will exceed 60px of height).

What I want to achieve is to display all the items centered vertically in their table row, here is the fiddle: https://jsfiddle.net/6sp5n7xg/.

HTML

<div class="wrapper">
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
        <li>Item 5<br />Item 6</li>
    </ul>
</div>

CSS

.wrapper {
    height: 300px;
    background-color: #EEE;
}

ul {
    display: table;
}

ul li {
    display: table-row;
    height: 60px;
}

Horizontally it works fine: https://jsfiddle.net/vq9mt02h/1/, but I want it also to be vertical.


Solution

  • Here a working example that starts from your code, only slightly modified. You must wrap each cell content in a span and set it display:table-cell;, moving to this selector also properties about height and vertical-align (I added also a red border to highlight middle alignement). So, here the modified code:

    HTML

    <div class="wrapper">
        <ul>
            <li><span>Item 1</span></li>
            <li><span>Item 2</span></li>
            <li><span>Item 3</span></li>
            <li><span>Item 4</span></li>
            <li><span>Item 5<br />Item 6</span></li>
        </ul>
    </div>
    

    CSS

    ul li {
        display: table-row;
    }
    
    ul li span {
        display: table-cell;
        height: 60px;
        border:solid 1px red;
        vertical-align:middle;
    }