html - 使绝对定位的 div 扩展父 div 高度

标签 html css position master-pages parent-child

正如您在下面的 CSS 中所见,我希望 child2 将自身定位在 child1 之前。这是因为我目前正在开发的网站也应该在移动设备上运行,child2 应该位于底部,因为它包含我想要的导航,位于移动设备上的内容下方。 - 为什么不是 2 个母版页?这是在整个 HTML 中重新定位的唯一 2 个 divs,因此这个微小更改的 2 个母版页是多余的。

HTML:

<div id="parent">
    <div class="child1"></div>
    <div class="child2"></div>
</div>

CSS:

parent { position: relative; width: 100%; }
child1 { width: auto; margin-left: 160px; }
child2 { width: 145px; position: absolute; top: 0px; bottom: 0px; }

child2 具有动态高度,因为不同的子站点可能有更多或更少的导航项。

我知道绝对定位的元素会从流中移除,因此会被其他元素忽略。
我尝试在父 div 上设置 overflow:hidden; ,但这没有帮助,clearfix 也没有。

我最后的手段是 JavaScript 来相应地重新定位两个 divs,但现在我会尝试看看是否存在非 JavaScript 的方式来做到这一点。

最佳答案

您自己回答了这个问题:“我知道绝对定位的元素已从流中删除,因此被其他元素忽略。”所以你不能根据绝对定位的元素来设置 parent 的高度。

你要么使用固定高度,要么需要 JS。

2022 年更新: 现在人们可能会使用 CSS flexbox[1] 或 grid[2] 来反转 HTML 元素内部的视觉顺序不使用 position: absolute;.

的父容器
  1. https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container#alignment_and_flex-direction
  2. https://developer.mozilla.org/en-US/docs/Web/CSS/grid或者 Reverse order of columns in CSS Grid Layout

关于html - 使绝对定位的 div 扩展父 div 高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12070759/

相关文章:

php - 如何刷新包含图像的div而不重新加载页面?

javascript - 证明内容 : flex-end; and flex-direction: column; are not working together

jquery - 带有包装 div 的淡入淡出图像

html - 如何正确对齐表格到中心?

css - 调整内容属性的图像大小

Java - 将元素添加到数组

jquery - 在DIV结束后使固定元素随内容滚动(滚动,不会一瞬间消失)

html - 将 Aria-hidden 更改为 "false"

html - 调整网页大小导致网站添加白底溢出

CSS 使 div 停留在页面底部