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

如何在移动端视图中使用CSS Grid将图片置于顶部?

移动端视图将图片置于顶部的CSS Grid解决方案

问题说明

需要在移动端视图中将图片置于顶部,当前使用CSS Grid布局但媒体查询未达到预期效果,缩小屏幕时布局错乱。

解决方案

核心是在媒体查询中调整Grid布局为单列,并修改元素排列顺序,同时适配移动端的内边距、容器高度等样式:

修改后的完整CSS代码

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background-color: hsl(233, 47%, 7%);
  font-size: 15px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  min-height: 100vh;
  margin: 1.5em;
}

.container {
  background-color: hsl(244, 38%, 16%);
  display: grid;
  grid-template-columns: 1fr 1fr;
  max-width: 1080px;
  padding: 0;
  margin: auto;
  overflow: hidden;
  border-radius: 0.5em;
}

.description {
  display: flex;
  flex-direction: column;
  padding: 4em;
}

.description h1 {
  font-family: "Inter", sans-serif;
  margin-bottom: 0.8em;
  padding-right: 3em;
}

.description p {
  font-family: "Lexend Deca", sans-serif;
  margin-bottom: 5em;
  color: hsla(0, 0%, 100%, 0.6);
  line-height: 1.8em;
  font-size: 13px;
  padding-right: 2em;
}

span {
  color: hsl(277, 64%, 61%);
}

.stats {
  display: flex;
  justify-content: space-between;
  padding-top: 1.9em;
  padding-right: 6em;
  margin-bottom: 1em;
}

h3 {
  font-family: "Inter", sans-serif;
  text-transform: uppercase;
  letter-spacing: 0.1em;
  margin-bottom: 0.3em;
  color: hsla(0, 0%, 100%, 0.75);
}

.stat p {
  text-transform: uppercase;
  font-size: 12px;
  color: hsla(0, 0%, 100%, 0.6);
}

.img-box {
  padding: 0;
}

.img-box img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  padding: 0;
}

/* 移动端媒体查询修改 */
@media (max-width: 700px) {
  .container {
    grid-template-columns: 1fr; /* 改为单列布局 */
    grid-template-rows: auto auto; /* 自动适应内容高度,避免固定值导致溢出 */
  }
  .img-box {
    order: -1; /* 将图片容器顺序提前,显示在内容上方 */
  }
  .description {
    padding: 2em; /* 缩小移动端内边距 */
    text-align: center; /* 移动端文本居中对齐 */
  }
  .description h1 {
    padding-right: 0; /* 移除标题右侧内边距 */
  }
  .description p {
    padding-right: 0; /* 移除段落右侧内边距 */
    margin-bottom: 2em; /* 减少段落下方间距 */
  }
  .stats {
    flex-direction: column; /* 统计项改为垂直排列 */
    padding-right: 0; /* 移除右侧内边距 */
    gap: 1.5em; /* 统计项之间添加间距 */
  }
}

.attribution {
  font-size: 11px;
  text-align: center;
}
.attribution a {
  color: hsl(277, 64%, 61%);
}

关键修改点

  • Grid布局调整:媒体查询中将grid-template-columns设为1fr实现单列布局,grid-template-rows改为auto auto让容器高度自适应内容,避免固定高度导致的溢出问题。
  • 元素顺序调整:给.img-box添加order: -1,无需修改HTML结构即可让图片在移动端显示在内容上方。
  • 移动端样式适配:缩小内容区内边距、文本居中、移除不必要的右侧内边距;统计项改为垂直排列并添加间距,适配移动端竖向排版。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 17:40:25