Search code examples
htmlcssvertical-alignmentcenteringtext-align

How to center text vertically and horizontally in between floated button elements?


I have a couple of buttons in a toolbar. They are floated to the left and right to give the middle-text 100% of the remaining width. Text could be one or two rows...

My problem is that I need to center the text and position it in the middle vertically.

MARKUP

<div class="toolbar">
<div class="button left">&nbsp;</div>
<div class="button left">&nbsp;</div>
<div class="button left">&nbsp;</div>
<div class="button right">&nbsp;</div>
<div class="button right">&nbsp;</div>
<span class="title">Start page title</span>
</div>

CSS

.left{
    float: left;
}
.right{
    float: right;
}
.toolbar{
    height: 70px;
    width: 500px;
    border: 1px solid red;
}
.button{
    width: 68px;
    height: 68px;
    border: 1px solid #fff;
    background: #666666;
}
.title{
    font-size: 12px;   
    line-height: 8px;
    vertical-align: middle;
    text-align: center;
}

I do have a fiddle as well (click a gray button to try it with dual row text): http://jsfiddle.net/U7LhL/6/

Any ideas? Setting line height wouldn't work (unless using JS) since height of the text is unknown and i need to fit 2 lines. Using absolute positioned text to achieve this would make it pretty messy I think, if even possible.

enter image description here


Solution

  • You can make the text container display: table-cell.

    body {
        background: pink;
    }
    .toolbar {
        display: table;
        height: 70px;
        width: 500px;
        border: 1px solid red;
    }
    .button {
        border: 1px solid #fff;
        width: 68px;
        height: 68px;
        background: #4679bd url(../img/logo.png) no-repeat -6% 50%;
    }
    .toolbar > div {
        display: table-cell;
    }
    .title {
        font-size: 12px;
        line-height: 8px;
        vertical-align: middle;
        text-align: center;
    }
    .center {
        vertical-align: middle;
        text-align: center;
    }
    

    Working Fiddle