Monday, February 14, 2011

div content vertical align center

Before jquery we struggled a lot to get div content vertically center in all browsers. But the wait is over; now we can have div content vertically centered with the help of a small jquery function.

Here is the code –

<style type="text/css">
.greenBorder{
    border: 1px solid green;
    height: 278px;
    width: 446px;
    text-align:center;
}
</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js" type="text/javascript"></script>

<script type="text/javascript">
$(function() {
// vertical align function
$.fn.vAlign = function() {
    return this.each(function(i){
        var ah = $(this).height();
        var ph = $(this).parent().height();       
        var mh = Math.ceil((ph-ah) / 2); //var mh = (ph - ah) / 2;
        $(this).css('margin-top', mh);
    });
};

$('.greenBorder img').vAlign();
//
});

</script>

<div class="greenBorder">
    <img src="11.jpg" alt="" title="" border="0" />           
</div>