【问题标题】:Positioning full-height absolute element inside relative one将全高绝对元素定位在相对元素内
【发布时间】:2017-01-12 17:45:43
【问题描述】:

请帮我解决这个任务。我们有 3 个 div 块。第一个 div 的高度设置为 100px(但在现实世界中它是动态值)。第二块具有固定的高度,并且有另一个块作为孩子。子块的高度应该延伸到屏幕底部。但是由于我们的第二个块是相对的,bottom:0 将意味着第二个块的底部。请问这种情况下的最佳实践是纯 CSS 吗?

body > div { height: 100px; }

.first { background: lightblue; }

.second {
  background: lightgreen;
  position: relative;
}

.second div {
  position: absolute;
  background: pink;
  width: 50%;
  height: 200px;
  top: 100px;
}
<div class="first">The height of the block may vary greately.</div>
<div class="second">
  <div>This DIV should take whole free space to the bottom of the screen.</div>
</div>

更新:

我可以通过将第二个 div 包装到额外的 div 中来实现效果(绝对宽度位置和底部:0)并将其保留为透明背景,但随后“其后面”的静态内容变得无法使用。这里是an example

【问题讨论】:

  • 哪个 div 应该占用剩余空间?第二个div还是第二个div的孩子?孩子的身高:200px。我想第二个会接受吗?
  • @jmag child 应该有剩余空间。 200px 是一个随机数。
  • 为什么不能有 3 个 div 在同一级别,而不是嵌套?
  • @Panglosee 因为嵌套的 div 是菜单的一部分。
  • 纯 css 的唯一方法是将嵌套的 div 固定到位置 - jsfiddle.net/eox0b8hq 因此高度不会受到相关容器的影响。

标签: html css css-position


【解决方案1】:

这是基于您的更新小提琴,因为不清楚您希望实现什么,但您提到此示例很接近,我将您的链接放在上面z-index 所以它是可点击的:

Check external Fiddle, embedded seems to break bottom

【讨论】:

  • 你可以在这里查看:jsfiddle.net/Syden/n725s1nq/1,因为 sn-p 把底部弄乱了。
  • 谢谢你,将尝试在我的项目中使用它。是的想法是第二个 div 是一个菜单,粉红色块是某种下拉菜单。并且该下拉菜单需要到达屏幕底部。但是第二块与顶部分开了一个额外的块。似乎我需要设置位置:相对于整个页面内容。由于第二个 div 几乎是全屏覆盖。
【解决方案2】:

body > div { height: 100px; }

.first { background: lightblue; }

.second {
  background-color: lightgreen;
  top: 100px;
}

.second >div {
  background: pink;
  width: 50%;
  height: 100%; 
}
<div class="first">The height of the block may vary greately.</div>
<div class="second">
  <div>This DIV should take whole free space to the bottom of the screen.</div>
</div>

【讨论】:

  • 我会尽量避免绝对的。
  • 感谢您的时间和精力,但很抱歉,这不是我需要的。
猜你喜欢
  • 2019-06-22
  • 1970-01-01
  • 2017-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-12
  • 1970-01-01
相关资源
最近更新 更多