Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to vertically align inline elements

I have this anchor tag that has text between to be vertically align text. I'm using this css attribute vertical-align: middle. Nothing happens tho.

like image 694
dave Avatar asked Mar 17 '11 23:03

dave


3 Answers

You can make it inline-block and give it a line-height:

a {
    line-height: 50px;
    display: inline-block;
}

JSFiddle with working example: http://jsfiddle.net/KgqJS/

like image 181
Bazzz Avatar answered Sep 27 '22 20:09

Bazzz


vertical-align only works on elements with display: table-cell, and that property value isn't supported in < IE8.

Known text

If you know the text to be centred, it is rather easy. You have two options.

<style type="text/css">
    #container {
        padding: 10px 0;
    }
</style>
<div id="container">
    Example of some lovely<br />
    multiline text.
</div>

You can use CSS's padding to add padding top and bottom, to make the text appear in the middle. This is useful for multiline text.

<style type="text/css">
    #container {
        height: 100px;
        line-height: 100px;
    }
</style>
<div id="container">
    Example
</div>

You can exploit the line-height property to make the text vertically centred. This only works with one line of text. You can guess what happens if there is more than 1.

Dynamic multiline text

Here is where things start to get somewhat tricky, and may have you crying for tables.

<style type="text/css">
    #container {
        display: table-cell;
        vertical-align: middle;
    }
</style>
<div id="container">
    <?php echo $content; ?>
</div>

Workaround for < IE8.

Source.

like image 42
alex Avatar answered Sep 27 '22 20:09

alex


<div><p>test test test test<p></div>

div{
    border:1px solid red;
    width:400px;
    height:400px;
    position:relative;
}


p{
    height:30px;
    position:absolute;
    top:50%;
    margin-top:-15px; /* negative half of height*/
}

Check working example at http://jsfiddle.net/Z2ssq/1/

like image 45
Hussein Avatar answered Sep 27 '22 20:09

Hussein