gpt4 book ai didi

javascript - 纯 JavaScript : Center an absolute position div in body

转载 作者:行者123 更新时间:2023-11-29 18:31:51 25 4
gpt4 key购买 nike

在不使用 jQuery 之类的库的情况下,将绝对位置 div 居中的最简单和最短的方法是什么。谢谢!

编辑:类似于 http://jsfiddle.net/apfwh/但也许更干净一点?

最佳答案

我认为不需要js。 CSS 会做(see here):

body {
background: #888;
}

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

UPD

如果您没有固定的元素宽度/高度:

JS(元素打开时):

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

CSS:

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

关于javascript - 纯 JavaScript : Center an absolute position div in body,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7379903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com