css - 当相对父项没有高度和宽度时,如何将绝对子项定位在相对父项中?

标签 css html

我正在尝试将 position:absolute div 放入 position:relative parent 中。在我的例子中,position:absolute div 是动态生成的。我想根据 position:absolute div 扩展 position:relative div。

这是例子,

#one {
  position:relative;
  background-color: pink;
}

#two {
  background-color: green;
  position: absolute;
  top:0px;
  left: 50px;
  width:100px;
  height:100px;
}

#three {
  background-color: yellow;
  position: absolute;
  top:100px;
  left: 50px;
  width:100px;
  height:100px;
}

#four {
  position:relative;
  background-color: violet;
  width:100px;
  height:50px;
}
<div id="one">
  <div id="two">First</div>
  <div id="three">Second</div>
</div>
<div id="four">Third</div>

在上面的示例中,div#one 没有高度和宽度,因此 div#four 与 div#two 重叠。我希望 div#four 应该放在 div#three 之后。

我搜索了答案,但无法从网络上获得任何答案。 谁能回答这个问题!

最佳答案

将 top 和 left 值添加到第四个相对定位的对象。

#one {
  position:relative;
  background-color: pink;
}

#two {
  background-color: green;
  position: absolute;
  top:0px;
  left: 50px;
  width:100px;
  height:100px;
}

#three {
  background-color: yellow;
  position: absolute;
  top:100px;
  left: 50px;
  width:100px;
  height:100px;
}

#four {
  position:relative;
  background-color: violet;
  width:100px;
  height:50px;
  top:200px;
  left: 50px;
}
<div id="one">
  <div id="two">First</div>
  <div id="three">Second</div>
</div>
<div id="four">Third</div>

关于css - 当相对父项没有高度和宽度时,如何将绝对子项定位在相对父项中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49791489/

相关文章:

html - 寻找具有这些功能的 3 列 CSS 模板

php - 将mysql结果的一行空格替换为 '-'

javascript - 如何比较两个 HTML 元素的渲染

html - 为什么这个动画不起作用?

javascript - 如何检索可视化放置在 div 下的元素

jQuery .css ('border' ) 在 Firefox 中不返回任何内容

javascript - 根据里面的&lt;iframe&gt;改变<div>的高度

html - BootStrap-下拉菜单

jquery - 图像同时淡入

c# - 将样式属性添加到 Html.BeginForm MVC/C#