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.
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.
Share Improve this question asked Aug 26, 2011 at 19:40 billabilla 2811 gold badge3 silver badges9 bronze badges4 Answers
Reset to default 8You 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.
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(); });
Here you go. Updated with a scroll event and consideration of document.body.scrollTop
http://jsfiddle/8Dupa/4/
$(window).scroll(function() { $('#box').center(); });
and within center()
top += document.body.scrollTop;
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();