开发者

Dead Centered Div

How is it possible to center a div both horizontally and vertically with respect to the screen, not the page. So that when the user scrolls down a long page, the div remains horizontally and vertically centered开发者_StackOverflow社区?


Here's a pure CSS solution, note the percentages and negative margins.

http://jsfiddle.net/R7Xy2/

div {
    position: fixed;
    width: 200px;
    height: 200px;
    top: 50%;
    left: 50%;
    margin-left: -100px;
    margin-top: -100px;
}


Here is your code

http://www.geekdaily.net/2007/07/04/javascript-cross-browser-window-size-and-centering/

just attach this event to window.onscroll. No need to use jQuery, try this

function addEvent(obj,ev,fn) {
  if(obj.addEventListener) obj.addEventListener(ev,fn,false);
  else if(obj.attachEvent) obj.attachEvent("on"+ev,fn);
}

addEvent(window,"scroll",yourfunction);

good luck


You may also try the following:

HTML markup:

<div class="classname">text here</div>

CSS:

.classname {
    position:absolute;
    left:50%;
    top:50%;
    padding:10px;
    border:1px solid #ccc;
}

The border and padding can be changed or removed on the basis of requirement. Also, make sure that the parent container must be positioned relatively, i.e. it should have position:relative.


CSS for the <div>:

position: absolute
left : (centerofpagepixel.x - (width of div /2));
top : (centerofpagepixel.y - (height of div/2));

Set the above using jQuery on the <div>.

You can calculate the centerofpagepixel.x and y using jQuery again. Probably get the width/height of the screen and divide them by 2.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜