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

移动端实现Label与Input分两行的CSS Grid布局问题排查

问题分析与解决方案

你的代码有两个核心问题,导致无法实现移动端标签独占一行、输入框容器在下方的布局效果:

  • 给.form-row设置了grid-template-columns: 1fr 2fr,这会让网格分成两列,标签和输入框容器会横向并排,而非上下堆叠。
  • grid-auto-rows: 30px, auto语法错误,CSS网格的行高设置不能用逗号分隔,需换成空格。

修正后的Grid布局方案

要达成需求,只需将网格列数改为1列,同时修正行高语法:

/* 基础样式,若需仅在移动端生效,可套媒体查询 */
.form-row {
  display: grid;
  grid-template-columns: 1fr; /* 单列布局,每个子元素自动占一行 */
  grid-auto-rows: 30px auto; /* 修正语法,用空格分隔行高 */
  padding: 12px 0 0 0;
  gap: 8px; /* 可选:添加间距优化视觉效果 */
}

/* 仅移动端生效的写法 */
@media (max-width: 768px) {
  .form-row {
    grid-template-columns: 1fr;
    grid-auto-rows: 30px auto;
    gap: 8px;
  }
}

HTML保持不变:

<div class="form-row">
  <label>Email address</label>
  <div style="width: 100%;">
    <input type="email" name="email">
  </div>
</div>

备选Flex布局方案

如果想用Flex实现同样效果,写法更简洁:

.form-row {
  display: flex;
  flex-direction: column; /* 子元素垂直排列 */
  padding: 12px 0 0 0;
  gap: 8px;
}

/* 仅移动端生效的写法 */
@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
    gap: 8px;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 11:55:16