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

标签 javascript html css flexbox centering

我有一个元素应该与另一个元素水平居中。居中元素的 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/

相关文章:

python - 使用 Beautiful Soup 和 Python 从搜索页面提取 HTML 内容

javascript - jQuery:克隆输入值及其样式

html - 高度 100% 不适用于所有浏览器

javascript - 如何防止滚动顶部在选项卡到隐藏元素时发生变化?

javascript - 如何将字典添加到列表中?

javascript - Html 表格行对齐

javascript - 删除 X 行之后的最后一行边框

html - 我的专栏将在 Firefox/Safari 中换行,但它在 Chrome 中有效

javascript - HTML/CSS 到 PDF,所有页面上的背景图片

javascript - 将路径 url 附加到 Javascript 对象