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 j开发者_Go百科sfiddle), but does not work. Can someone help me with it? Thanks.
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.
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.net/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();
精彩评论