billa
billa

Reputation: 281

jQuery: keep a div in page center, even if page is scrolled down

I want to center a div on the screen so that when the page is scrolled down/up, the div scrolls smoothly to the center of the page. I am trying this code (please see jsfiddle), but does not work. Can someone help me with it? Thanks.

Upvotes: 2

Views: 9198

Answers (4)

atabak
atabak

Reputation: 193

use this plugin:

jQuery.fn.center = function(){
this.css("position","absolute");
this.css("top","50%");
this.css("left","50%");
this.css("margin-top","-"+(this.height()/2)+"px");
this.css("margin-left","-"+(this.width()/2)+"px");
return this;}

$("#id").center();

Upvotes: 1

Neil
Neil

Reputation: 1206

Here you go. Updated with a scroll event and consideration of document.body.scrollTop

http://jsfiddle.net/8Dupa/4/

$(window).scroll(function() { $('#box').center(); });

and within center()

top += document.body.scrollTop;

Upvotes: 1

Senad Meškin
Senad Meškin

Reputation: 13756

You don't need jquery for that, just use css

HTML

<div id="senad">content</div>

CSS

 #senad { width: 200px; height: 200px; position: fixed; top: 50%; left: 50%; border: 1px solid gray;}

Thi will keep element on center.

Upvotes: 8

Tejs
Tejs

Reputation: 41246

Why not just mark it position: fixed and keep it there regardless of where the user scrolls? Then you don't need any form of javascript trickery.

However, to answer your current problem, it seems you provide the centering once, you you never react to the scroll event of the window:

 $(window).scroll(function() { $('#box').center(); });

Upvotes: 6

Related Questions