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


当前回答

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

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

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

其他回答

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

这和@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/

使用纯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>

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 */
}

这应该对你有用。

还可以考虑下一个方法:

CSS:

.parent {
  height: 100%;
}
.parent:after {
  content: '';
  display: block;
}

另外,因为你试图重新定位div考虑css网格