Rogério Lino

Web development and tips

jQuery: Horizontal + Vertical Align

Função jQuery para alinhar horizontalmente e verticalmente o elemento.

1
2
3
4
5
6
7
8
9
jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css({
        top: '50%',
        left: '50%',
        margin: '-' + (this.height() / 2) + 'px 0 0 -' + (this.width() / 2) + 'px'
    });
    return this;
}

Exemplo:

1
2
3
<div id="centered_div">
    <p>My div content here</p>
</div>
1
$('#centered_div').center()

Edit on jsFiddle: http://jsfiddle.net/rc6kS/

Comments