正如你在下面的CSS中看到的,我想让child2将自己定位在child1之前。这是因为我目前正在开发的网站也应该在移动设备上工作,其中child2应该在底部,因为它包含了我想在移动设备上的内容下面的导航。-为什么不是2本杰作?这是在整个HTML中唯一被重新定位的2个div,所以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上,但这没有帮助,clearfix也没有。

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


当前回答

试试这个,对我很管用

.child {
    width: 100%;
    position: absolute;
    top: 0px;
    bottom: 0px;
    z-index: 1;
}

它将把子高度设置为父高度

其他回答

有一个很简单的方法可以解决这个问题。

你只需要在相对div中复制child1和child2的内容,在父div中使用display:none。使用child1_1和child2_2。把child2_2放在上面,child1_1放在下面。

当你的jquery(或任何东西)调用绝对div,只需设置相应的相对div (child1_1或child2_2)与display:block和可见性:隐藏。相对子元素仍然是不可见的,但是会使父元素的div更高。

我也遇到过类似的问题。 为了解决这个问题(而不是使用正文、文档或窗口计算iframe的高度),我创建了一个div来包装整个页面内容(例如,一个带有id="page"的div),然后我使用它的高度。

现在有更好的办法了。你可以使用bottom属性。

    .my-element {
      position: absolute;
      bottom: 30px;
    }

这个问题是在2012年flexbox出现之前提出的。使用现代CSS解决这个问题的正确方法是使用媒体查询和移动设备的伸缩列反转。不需要绝对定位。

https://jsfiddle.net/tnhsaesop/vjftq198/3/

HTML:

<div class="parent">
  <div style="background-color:lightgrey;">
    <p>
      I stay on top on desktop and I'm on bottom on mobile
    </p>
  </div>
  <div style="background-color:grey;">
    <p>
      I stay on bottom on desktop and I'm on top on mobile
    </p>
  </div>
</div>

CSS:

.parent {
  display: flex;
  flex-direction: column;
}

@media (max-width: 768px) {
  .parent {
    flex-direction: column-reverse;
  }
}

使用纯JavaScript,您只需要使用getComputedStyle()方法检索静态位置子元素.child1的高度,然后使用HTMLElement将检索值设置为相同子元素的填充顶部。样式属性。


检查并运行下面的代码片段作为我上面描述的一个实际示例:

/* JavaScript */ var child1 = document.querySelector(".child1"); var parent = document.getElementById("parent"); var childHeight = parseInt(window.getComputedStyle(child1).height) + "px"; child1.style.paddingTop = childHeight; /* CSS */ #parent { position: relative; width: 100%; } .child1 { width: auto; } .child2 { width: 145px; position: absolute; top: 0px; bottom: 0px; } html, body { width: 100%;height: 100%; margin: 0; padding: 0; } <!-- HTML --> <div id="parent"> <div class="child1">STATIC</div> <div class="child2">ABSOLUTE</div> </div>