给定一个模板,HTML不能修改,因为其他要求,如何可能显示(重新安排)一个div上面的另一个div时,他们不是在HTML的顺序?两个div都包含高度和宽度不同的数据。

<div id="wrapper">
    <div id="firstDiv">
        Content to be below in this situation
    </div>
    <div id="secondDiv">
        Content to be above in this situation
    </div>
</div>
Other elements

希望期望的结果是显而易见的:

Content to be above in this situation
Content to be below in this situation
Other elements

当尺寸是固定的,很容易定位他们在需要的地方,但我需要一些想法,当内容是可变的。为了实现这个场景,请将两者的宽度都考虑为100%。

我特别寻找一个css唯一的解决方案(它可能必须满足其他解决方案,如果它不成功)。

接下来还有其他因素。考虑到我演示的有限场景,我提到了一个很好的建议——考虑到它可能是最好的答案,但我也希望确保后面的元素不受影响。


当前回答

负的顶部边距可以达到这种效果,但是需要为每一页定制。例如,这个标记…

<div class="product">
<h2>Greatest Product Ever</h2>
<p class="desc">This paragraph appears in the source code directly after the heading and will appear in the search results.</p>
<p class="sidenote">Note: This information appears in HTML after the product description appearing below.</p>
</div>

...这个CSS…

.product { width: 400px; }
.desc { margin-top: 5em; }
.sidenote { margin-top: -7em; }

…你可以把第二段放在第一段上面。

当然,您必须手动调整CSS以适应不同的描述长度,以便介绍段跳跃适当的数量,但如果您对其他部分的控制有限,而对标记和CSS有完全的控制,那么这可能是一个选择。

其他回答

这里有一个解决方案:

<style>
#firstDiv {
    position:absolute; top:100%;
}
#wrapper {
    position:relative; 
}

但我怀疑您有一些内容遵循包装器div…

正如其他人所说,这不是你想在CSS中做的事情。你可以用绝对的定位和奇怪的边际来蒙混过关,但这不是一个可靠的解决方案。在您的情况下,最好的选择是转向javascript。在jQuery中,这是一个非常简单的任务:

$('#secondDiv').insertBefore('#firstDiv');

或者更一般地说:

$('.swapMe').each(function(i, el) {
    $(el).insertBefore($(el).prev());
});

这只能用CSS来完成!

请检查我对这个类似问题的回答:

https://stackoverflow.com/a/25462829/1077230

我不想重复我的答案,但它的简短是,父元素需要成为一个flexbox元素。例如:

(此处仅使用webkit供应商前缀)

#main {
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-flex-direction: column;
    flex-direction: column;
    -webkit-box-align: start;
    -webkit-align-items: flex-start;
    align-items: flex-start;
}

然后,通过指示它们的顺序来交换div:

#main > div#one{
    -webkit-box-ordinal-group: 2;
    -moz-box-ordinal-group: 2;
    -ms-flex-order: 2;
    -webkit-order: 2;
    order: 2;
    overflow:visible;
}

#main > div#two{
    -webkit-box-ordinal-group: 1;
    -moz-box-ordinal-group: 1;
    -ms-flex-order: 1;
    -webkit-order: 1;
    order: 1;
}

仅为移动设备订购,并保持桌面本机顺序:

/ / html

<div>
  <div class="gridInverseMobile1">First</div>
  <div class="gridInverseMobile1">Second</div>
</div>

/ / css

@media only screen and (max-width: 960px) {
  .gridInverseMobile1 {
    order: 2;
    -webkit-order: 2;
  }
  .gridInverseMobile2 {
    order: 1;
    -webkit-order: 1;
  }
}

结果:

Desktop: First | Second
Mobile: Second | First

来源:https://www.w3schools.com/cssref/css3_pr_order.asp

在CSS中,将第一个div向左或向右浮动。第二个div与第一个div一样向左或向右浮动。应用clear:向左或向右,与上面两个div的第二个div相同。

例如:

#firstDiv {
    float: left;
}

#secondDiv {
    float: left;
    clear: left;
}