ShibinRagh
ShibinRagh

Reputation: 6646

Div need vertical center of the screen after page scrolling

I have a div which needs to be vertically centered in the screen after page scrolling

Here's a demo - http://jsfiddle.net/JtZ7F/

<div style="height:1000px; border:1px solid red;">
    scroll
    <span style="height:150px; width:100px; float:right; border:1px solid green; display:block; position:fixed;top:50%; margin-top:-75px;">
        need vertical center of the screen after page scroling
    </span>
</div>

Now I am using position:fixed;, it's not a solution

I want when I stop the page scrolling my green box smoothly moves to vertical center of the screen.

How can I do this in jQuery?

Upvotes: 3

Views: 8229

Answers (2)

Sam Jones
Sam Jones

Reputation: 4618

Here's how I do it, tested in Chrome & IE7+, see jsfiddle for an example.

$.fn.center = function () {
                    return this.css({
                        'left': ($(window).width() / 2) - $(this).width() / 2,
                        'top': ($(window).height() / 2) - $(this).height() / 2,
                        'position': 'fixed'
                    });
                };

Usage:

$(document).ready(function(){ 
    $(element).center();
});

Upvotes: 3

TRR
TRR

Reputation: 1643

Add this function in your jquery :

jQuery.fn.center = function () {   
this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");    
 this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");     return this; } 

Add a id to your span "test" and write the below in document.ready

$(document).ready(function(){    
$('#test').center(); 
});

Upvotes: 4

Related Questions