Vertical-Align a DIV

2019-07-18 11:50发布

问题:

This is the code for my next/prev navigation found at http://ilikeyou.tk/763/ :

<div class="navigation">
    <a href="<?echo $site;?><?echo$prevs['id']?>" class="prev" title="Previous Like"></a>
    <? if($nexts['id'] == ''){ ?>

    <? }else{ ?>
        <a href="<?echo $site;?><?echo$nexts['id']?>" class="next" title="Next Like"></a>
    <? } ?>
</div>

I would like to vertically center the buttons. I tried using vertical-align:middle; which didn't work. I also tried top:50%; but that didn't do the job either.

Here is my css:

.navigation {
    position: relative;
    float: left;
    vertical-align : middle;
    height: auto;
    padding: 0;
    margin: 0 -20px 0 -22px;
    width: 636px;
    z-index:1;
}

.navigation a.prev{
    background: url('images/nav_left.png');
    float: left;
    width: 50px;
    height: 50px;
    margin-left:10px;
}

.navigation a.next {
    background: url('images/nav_right.png');
    float: right;
    width: 50px;
    height: 50px;
    margin-right:10px;
}

Thanks!

回答1:

So, I'm guessing that the content area height is not very static.

http://jsfiddle.net/aBzhu/

Trick is to have the outer element set to position: relative; float: left; and then the element you want to center as position: absolute; top: 50%; margin-top: -Half_the_height_of_this_element;

Note that this only works when the element that you want to center vertically IS static height. Should fit your usage I think.

Edit: Oh.. and I dont think this necessarily works in ie6. But does work ie7+

Edit2: Also if youre not interested in such a puny methods you should check this out Using jQuery to center a DIV on the screen



回答2:

vertical-align is intended for table cell rendering, and even this is quite problematic. Why not just add a few pixels of top padding to your navigation ul? It's not real centering, but you're obviously not worried about dunamic scaling when you're using a fixed height graphic for the navigation background.



回答3:

This Solution Matched me perfectly for small texts. Even if it is a link or just a text inside the div, this CSS Class could vertically align the content inside the DIV. Works for IE as well..

 .verticalCenterDivText{
        height: 29px;
        line-height: 29px;
    }

Hope this helps....

Regards, ADynaMic