gpt4 book ai didi

javascript - 使一个元素相对于另一个元素居中

转载 作者:太空宇宙 更新时间:2023-11-04 09:22:56 25 4
gpt4 key购买 nike

我有一个元素应该与另一个元素水平居中。居中元素的 CSS 是这样的(我删除了不必要的代码):

#center-element{
display: flex;
flex-direction: column;
align-items: stretch;
position: absolute;
}

我必须使用 vanilla JS 来做到这一点。我试过:

var targetPos = target.getBoundingClientRect();
centerDiv.style.top = (targetPos.top + targetPos.height) + "px";
centerDiv.style.left = (targetPos.left + (targetPos.width / 2)) + "px";

但那是关闭的。有什么想法吗?

JSFiddle

最佳答案

//Somehow center the div here
var target = document.getElementById("target");
var centerDiv = document.getElementById("centerDiv");
var targetPos = target.getBoundingClientRect();
centerDiv.style.top = targetPos.bottom + "px";
centerDiv.style.left = targetPos.left + (target.offsetWidth - centerDiv.offsetWidth) / 2 + "px";
#target {
background-color: lightblue;
text-align: center;
width: 75%;
}
#centerDiv {
display: flex;
flex-direction: column;
align-items: stretch;
position: absolute;
}
<div id="target">
This is the div
</div>
<div id="centerDiv">
This is supposed to be horizontally centered <em>to the div element above</em>
</div>

关于javascript - 使一个元素相对于另一个元素居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41374043/

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