给定一个模板,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唯一的解决方案(它可能必须满足其他解决方案,如果它不成功)。

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


当前回答

这可以使用Flexbox来完成。

创建一个同时应用display:flex和flex-flow:column-reverse的容器。

/* -- Where the Magic Happens -- */ .container { /* Setup Flexbox */ display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; /* Reverse Column Order */ -webkit-flex-flow: column-reverse; flex-flow: column-reverse; } /* -- Styling Only -- */ .container > div { background: red; color: white; padding: 10px; } .container > div:last-of-type { background: blue; } <div class="container"> <div class="first"> first </div> <div class="second"> second </div> </div>

来源:

https://css-tricks.com/using-flexbox/ https://developer.mozilla.org/en-US/docs/Web/CSS/flex-flow#Browser_compatibility

其他回答

CSS唯一解决方案 1. 包装的高度应固定或 2. 第二个div的高度应该固定

在支持pre-flexbox用户代理(主要是旧IE)的同时,绝对没有办法通过CSS来实现你想要的东西——除非:

您知道每个元素的精确渲染高度(如果是这样,您可以完全定位内容)。如果您正在处理动态生成的内容,那么您就不走运了。 你知道这些元素的确切数量。同样,如果您需要对动态生成的多个内容块执行此操作,那么您就不走运了,特别是当内容块超过三个左右时。

如果以上为真,那么您可以通过对元素的绝对定位来做您想做的事情

#wrapper { position: relative; }
#firstDiv { position: absolute; height: 100px; top: 110px; }
#secondDiv { position: absolute; height: 100px; top: 0; }

同样,如果你不知道至少#firstDiv的高度,你无法通过CSS单独做你想做的事情。如果这些内容是动态的,则必须使用javascript。

如果您知道,或者可以强制将成为upper元素的大小,则可以使用

position : absolute;

在你的css中,给divs他们的位置。

否则javascript似乎是唯一的出路:

fd = document.getElementById( 'firstDiv' );
sd = document.getElementById( 'secondDiv' );
fd.parentNode.removeChild( fd );
sd.parentNode.insertAfter( fd, sd );

或者类似的东西。

编辑:我刚刚发现这可能是有用的:w3文档css3移动到

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

<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有完全的控制,那么这可能是一个选择。

仅css的解决方案(适用于IE10+) -使用Flexbox的order属性:

演示:http://jsfiddle.net/hqya7q6o/596/

#flex{显示:flex;flex-direction:列;} #a {order: 2;} #b {order: 1;} #c {order: 3;} flex < div id = " " > < div id = " " > < / div > b < div id = " b " > < / div > c < div id = " c " > < / div > < / div >

更多信息:https://developer.mozilla.org/en-US/docs/Web/CSS/order