Vertically Centering Text in a Fixed-Size Element With No Overflow

Most of the blog posts/tutorials on the web that show you how to center text vertically using either line-height (only works for a single line of text) or using display: table-cell which allows the text to exceed a fixed size (table cells are allowed to get taller than their height if the text is long). Here’s a version that clips the overflow by surrounding the display: table-cell element in a containing div.

Vertically centered text in fixed sized boxes

<style>
    /* Wrapper exists to prevent long text exceeding the bounding box. */
    .wrapper {
        /* height and width here act as a maximum for when the text is very long. */
        height: 100px;
        width: 100px;
        overflow: hidden;
        background: #eee; /* just so we can see what's going on in the demo */
    }
    /* Cell does the work of allowing us to vertical-align: middle. */
    .cell {
        /* height and width here act as a minimum for when the text is not long. */
        height: 100px; /* subtract any padding on wrapper from height and width here */
        width: 100px;
        display: table-cell;
        text-align: center;
        vertical-align: middle;
    }
</style>

<div class="wrapper">
        <div class="cell">
            This is a test.
        </div>
</div>
<hr>
<div class="wrapper">
        <div class="cell">
            This is a test with much longer text.  This is a test with much longer text.  This is a test with much longer text.  This is a test with much longer text.  This is a test with much longer text.
    </div>
</div>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.