You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Media Query实现动态布局?移动端纯CSS布局调整求助

纯CSS实现移动端布局调整:将SectionC移至SectionA与SectionB之间

需求回顾

PC端布局:SectionA和SectionB横向排列,SectionC在二者下方;
移动端布局:需要把SectionC调整到SectionA和SectionB之间,要求仅用CSS完成,不依赖JavaScript。

解决方案

核心思路是给最外层容器添加flex布局,借助flex的order属性重新定义元素的排列顺序,无需修改原有HTML结构。

修改后的代码

HTML(仅给最外层容器加class,其余不变)

<div class="container">
  <div class="header">
    <div>
      SectionA
    </div>
    <div>
      SectionB
    </div>
  </div>
  <div class="bottom">
    SectionC
  </div>
</div>

CSS

/* PC端布局保持原有逻辑 */
.container {
  display: block;
}

.header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  background-color: #d7d7d7;
}

.bottom {
  background-color: #ffd5d5;
}

/* 移动端布局调整 */
@media screen and (max-width: 760px) {
  .container {
    display: flex;
    flex-direction: column;
  }
  
  .header {
    flex-direction: column;
  }
  
  /* 通过order属性重新排序 */
  .header > div:first-child { /* SectionA */
    order: 1;
  }
  .bottom { /* SectionC */
    order: 2;
  }
  .header > div:last-child { /* SectionB */
    order: 3;
  }
}

原理说明

  • 移动端将最外层.container设为flex容器,方向改为纵向排列;
  • order属性控制flex容器内元素的显示顺序,数值越小越靠前;
  • 给SectionA设order:1,SectionC设order:2,SectionB设order:3,就能实现A→C→B的移动端布局。

内容的提问来源于stack exchange,提问作者sjm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 19:15:54