简体   繁体   中英

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.

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(); });

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();

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM