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

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


当前回答

如果您想反转子元素的显示顺序。我建议你用这个

方向:rtl;//从右向左

在父元素中设置此属性

其他回答

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

<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真的不应该被用来重构HTML后端。然而,如果你知道所涉及的两个元素的高度,并且感觉很笨拙,这是可能的。此外,当在div之间进行时,文本选择将会混乱,但这是因为HTML和CSS的顺序是相反的。

#firstDiv { position: relative; top: YYYpx; height: XXXpx; }
#secondDiv { position: relative; top: -XXXpx; height: YYYpx; }

其中XXX和YYY分别是firstDiv和secondDiv的高度。这将适用于后面的元素,不像顶部的答案。

我有一个简单的方法。

<!--  HTML  -->

<div class="wrapper">

    <div class="sm-hide">This content hides when at your layouts chosen breaking point.</div>

    <div>Content that stays in place</div>

    <div class="sm-show">This content is set to show at your layouts chosen breaking point.</div>

</div>

<!--  CSS  -->

    .sm-hide {display:block;}
    .sm-show {display:none;}

@media (max-width:598px) {
    .sm-hide {display:none;}
    .sm-show {display:block;}
}

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

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

我正在寻找一种方法来改变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
});