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

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


当前回答

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

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

或者更一般地说:

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

其他回答

我正在寻找一种方法来改变divs的顺序,只针对移动版本,这样我就可以很好地设计它。多亏了nickf的回复,我才能让这段代码很好地满足了我的需求,所以我想和你们分享一下:

//  changing the order of the sidebar so it goes after the content for mobile versions
jQuery(window).resize(function(){
    if ( jQuery(window).width() < 480 )
    {
        jQuery('#main-content').insertBefore('#sidebar');
    }
    if ( jQuery(window).width() > 480 )
    {
        jQuery('#sidebar').insertBefore('#main-content');
    }
    jQuery(window).height(); // New height
    jQuery(window).width(); // New width
});

仅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

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

好吧,通过一些绝对的定位和一些狡猾的边缘设置,我可以接近,但它并不完美或漂亮:

#wrapper { position: relative; margin-top: 4em; }
#firstDiv { position: absolute; top: 0; width: 100%; }
#secondDiv { position: absolute; bottom: 0; width: 100%; }

“margin-top: 4em”是特别讨厌的部分:这个边距需要根据firstDiv的内容量进行调整。根据你的具体要求,这是可能的,但我希望有人能在这个基础上建立一个固溶体。

Eric关于JavaScript的评论应该继续下去。

只需通过指定display: flex和flex-direction: column为父div使用flex。 然后使用order来确定哪个子div先出现