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

如何编写适配移动端与平板端的Flex响应式CSS

Flex布局响应式适配失效:移动端垂直堆叠/平板端水平换行问题

需求说明

需要实现以下响应式效果:

  • 移动端:Div盒子垂直排列(上下堆叠)
  • 平板端:Div盒子水平排列,超出容器时自动换行

当前使用flex-direction的row/column属性配置后未生效,相关代码如下:

原CSS代码

.flex-container {
  display: flex;
}

.flex-child {
  flex: 1;
  border: 2px solid yellow;
  background-color: blueviolet;
  width: 150px;
  height: 150px; 
}  

/* For Tablet View */
@media screen and (min-device-width: 768px) and (max-device-width: 1024px) {
  .flex-container {
    flex-direction: row;
  }
}

/* For Mobile Portrait View */
@media screen and (max-device-width: 480px) and (orientation: portrait) {
  .flex-container {
    flex-direction: column;
  }
}

/* For Mobile Landscape View */
@media screen and (max-device-width: 640px) and (orientation: landscape) {
  .flex-container {
    flex-direction: row;
  }
}

/* For Mobile Phones Portrait or Landscape View */
@media screen and (max-device-width: 640px) {
  .flex-container {
    flex-direction: row;
  }
}

原HTML代码

<div class="flex-container">
  <div class="flex-child magenta">Flex Column 1</div>
  <div class="flex-child green">Flex Column 2</div>
  <div class="flex-child green">Flex Column 3</div>
  <div class="flex-child green">Flex Column 4</div>
  <div class="flex-child green">Flex Column 5</div>
  <div class="flex-child green">Flex Column 6</div>
</div>

问题分析与解决方案

核心问题点

  1. 媒体查询规则冲突:原代码中多个移动端媒体查询优先级重叠,后面的max-device-width:640px规则覆盖了竖屏的column配置,导致移动端始终显示row。
  2. 错误使用device-width:max-device-width指向设备物理宽度,而非浏览器视口宽度,响应式适配应使用max-width更准确。
  3. 缺少换行配置:平板端未设置flex-wrap: wrap,子元素超出容器时会挤压变形,无法自动换行。
  4. flex:1的副作用:在column布局下,flex:1会让子元素高度自动拉伸,不符合垂直堆叠的预期效果。

修正后的代码

.flex-container {
  display: flex;
  /* 平板端默认水平排列,超出自动换行 */
  flex-direction: row;
  flex-wrap: wrap;
  gap: 8px; /* 可选,添加子元素间距 */
}

.flex-child {
  border: 2px solid yellow;
  background-color: blueviolet;
  width: 150px;
  height: 150px;
  /* 保持子元素固定宽高,避免拉伸 */
  flex: 0 0 auto;
}

/* 移动端适配:屏幕宽度≤767px时垂直排列 */
@media screen and (max-width: 767px) {
  .flex-container {
    flex-direction: column;
    align-items: flex-start; /* 可选:让子元素左对齐,默认是拉伸占满宽度 */
  }
  .flex-child {
    /* 可选:让移动端子元素占满容器宽度 */
    width: 100%;
  }
}

代码说明

  • 采用移动优先的反向思路:默认实现平板端的水平换行效果,再通过媒体查询覆盖移动端的垂直布局。
  • 使用max-width替代max-device-width,适配浏览器视口变化(比如桌面端缩放窗口)。
  • 添加flex-wrap: wrap确保平板端子元素超出时自动换行。
  • 重置flex:0 0 auto避免子元素在不同布局下被拉伸变形,同时可根据需求调整移动端子元素宽度(比如占满容器)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 23:10:18