【问题标题】:How to position absolute children inside relative parent, when relative parent does not have height and width?当相对父级没有高度和宽度时,如何在相对父级内定位绝对子级?
【发布时间】:2018-06-01 15:49:46
【问题描述】:

我正在尝试适应位置:绝对 div 的内部位置:相对父级。在我的情况下,位置:绝对 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 之后。

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

【问题讨论】:

  • 为什么需要使用 position:absolute ?

标签: css html


【解决方案1】:

将顶部和左侧值添加到您的第四个相对定位的对象。

#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>

【讨论】:

  • 您好 Vineeta,感谢您的回复。实际上我试图在下面对齐 div#four 而不添加顶部或左侧位置。有没有可能这样做?
【解决方案2】:

这是你想要的吗?

#one {
  background-color: pink;
  padding-left: 50px;
}

#two {
  background-color: green;
  width:100px;
  height:100px;
}

#three {
  background-color: yellow;
  width:100px;
  height:100px;
}

#four {
  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>

如果是这种情况,您就不需要#two#three 的绝对定位。让它们流入static(默认位置)。如果您需要它们距离#one 开头的左侧 50px,您可以在 #one 上添加一个 padding-left,或者在 #two#three 上添加一个 margin-left,或者将它们放在相对位置上,而不是绝对的,并保持left: 50px;

其实你可以看到我根本没有改变任何position。默认的static 完全符合您的要求。

【讨论】:

  • 您好 Jordi,感谢您的快速回复。在这里我正在寻找对齐位置的答案:绝对div的内部位置:相对div。我知道,我看到你的答案有效!但这不是我要找的。再次感谢!
  • 好吧,在这种情况下,您遇到了经典的折叠容器问题,我建议您阅读有关浮动/绝对元素和 clearfix hack 的内容。但是,再一次,我认为你太过分了。如果你有问题要解决,请选择最简单的解决方案。 UX/UI 会对你说:我希望它看起来和表现得像这样,但不应该说我想要绝对定位的 div。在这种特定情况下,您尝试以复杂的方式获取默认行为。
猜你喜欢
  • 2013-12-30
  • 1970-01-01
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-19
相关资源
最近更新 更多