正如你在下面的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的方式来做到这一点。


当前回答

这个问题是在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;
  }
}

其他回答

Feeela是对的,但是你可以让父div收缩或扩展到子元素,如果你像这样反转div的定位:

.parent {
    position: absolute;
    /* position it in the browser using the `left`, `top` and `margin` 
       attributes */
}

.child {
    position: relative;
    height: 100%;
    width: 100%;

    overflow: hidden;
    /* to pad or move it around using `left` and `top` inside the parent */
}

这应该对你有用。

你自己回答了这个问题:

我知道绝对定位的元素被从流中移除,因此被其他元素忽略。

你不能根据绝对定位元素来设置父元素的高度。

要么使用固定高度,要么使用JavaScript。

现在,人们可能会使用CSS flexbox或网格布局来反转父容器内HTML元素的可视顺序,而不使用position: absolute;。参见CSS网格布局中列的反向顺序

绝对视图将自己定位在最近的不是静态定位的祖先(position: static)上,因此如果你想让一个绝对视图定位在给定的父视图上,将父视图的位置设置为相对,将子视图的位置设置为绝对

这和@ChrisC的建议非常相似。它不是使用绝对定位元素,而是使用相对定位元素。也许对你有用

<div class="container">
  <div class="my-child"></div>
</div>

你的css是这样的:

.container{
    background-color: red;
    position: relative;
    border: 1px solid black;
    width: 100%;
}

.my-child{
    position: relative;
    top: 0;
    left: 100%;
    height: 100px;
    width: 100px;
    margin-left: -100px;
    background-color: blue;
}

https://jsfiddle.net/royriojas/dndjwa6t/

我想出了另一个解决方案,虽然我不喜欢,但却能完成任务。

基本上以不可见的方式复制子元素。

<div id="parent">
    <div class="width-calc">
        <div class="child1"></div>
        <div class="child2"></div>
    </div>

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

CSS:

.width-calc {
    height: 0;
    overflow: hidden;
}

如果这些子元素包含很少的标记,那么影响就会很小。