我想将一个 div 置于父 div 的中心。我能做到的唯一方法是使用 margin-left
属性。公式为:
margin-left = (parent.width/2) - (child.width/2)
但由于两件事,我无法通过 JavaScript 完成它:
样式中未定义宽度,因此无法通过
document.getElementById("child").style.width
访问
document.getElementById("child").offsetWidth
出于未知原因未提供正确和正确的宽度
我正在使用这段代码,但如上所述,它不起作用
<script type="text/javascript">
document.getElementById("fb_share").style.marginLeft = parseInt((document.getElementById("vss_border").offsetWidth / 2) - (document.getElementById("fb_share").offsetWidth / 2)) + "px";
</script>
如果有任何其他通过 CSS 的解决方案(但它必须是 margin-left 并且没有宽度变化)请告诉。
最佳答案
既然你说了 JavaScript,我就不能不提 jQuery 的 position function :
$("#myDiv").position({
my: "center",
at: "center",
of: $('#parent')
});
关于javascript - 使用 JavaScript 在父 div 中居中 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6464967/