开发者

Pure JavaScript: Center an absolute position div in body

What's the easiest and shortest way to center an absolute position div in the body without using a library like jQuery. Thank you!

Edit: Somet开发者_C百科hing like http://jsfiddle.net/apfwh/ but maybe with a bit cleaner?


I think no js needed. CSS will do it (see here):

body {
    background: #888;
}

.box {
    width: 100px;
    height: 100px;
    background: #ccc;
    position: absolute;
    left: 50%;
    top: 50%;
    margin: -50px 0 0 -50px;
}

UPD

In case you don't have fixed width/height of element:

JS (when element is opened):

element.style.margitLeft = -element.offsetWidth / 2
element.style.margitTop = -element.offsetHeight / 2

CSS:

.box {
    background: #ccc;
    position: fixed;
    left: 50%;
    top: 50%;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜