如何用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
相关产品推荐
相关产品推荐

