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

如何实现子div贴合父div边缘的响应式天气卡片布局

解决方案

问题出在.weather-container的justify-content: center属性上——flex布局会在子元素未占满一行时,把剩余空白均匀分配到子元素两侧,导致边缘间距变大。要实现"空间不足就直接换行"的效果,按以下步骤修改:

关键修改点

  1. 将容器对齐方式改为左对齐,取消自动分配空白空间
  2. 通过媒体查询,根据屏幕宽度控制每行显示的卡片数量,确保卡片始终贴合容器边缘
  3. 适配换行后的分隔线显示逻辑,每行最后一个卡片不再显示右侧分隔线

修改后的CSS代码

body {
  font-family: Arial, sans-serif;
  text-align: center;
  margin-top: 50px;
}

.weather-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start; /* 核心修改:左对齐,不再分配空白 */
  align-items: center;
  margin: 0 auto;
  padding: 10px;
  border-radius: 15px;
  border: 2px solid #000;
  max-width: 100%;
  background-color: #fff;
  box-sizing: border-box; /* 确保padding算入容器总宽度 */
}

.weather-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 10px 20px;
  width: calc(100% / 12); /* 默认每行12个卡片 */
  background-color: #fff;
  position: relative;
  box-sizing: border-box; /* 确保padding算入卡片总宽度 */
}

.weather-icon {
  font-size: 36px;
}

.temperature {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-top: 5px;
  font-size: 18px;
}

.temperature span {
  width: 45%;
  text-align: center;
}

.month-label {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 5px;
}

.separator {
  position: absolute;
  top: 0;
  right: 0;
  width: 2px;
  height: 100%;
  background-color: #000;
}

/* 默认隐藏最后一个卡片的分隔线 */
.weather-box:last-child .separator {
  display: none;
}

/* 平板端:每行显示6个,分成2行 */
@media (max-width: 992px) {
  .weather-box {
    width: calc(100% / 6);
  }
  /* 每行第6个卡片隐藏分隔线 */
  .weather-box:nth-child(6n) .separator {
    display: none;
  }
}

/* 移动端:每行显示4个,分成3行 */
@media (max-width: 576px) {
  .weather-box {
    width: calc(100% / 4);
  }
  /* 每行第4个卡片隐藏分隔线 */
  .weather-box:nth-child(4n) .separator {
    display: none;
  }
}

效果说明

  • 桌面端:每行显示12个卡片,完全贴合容器边缘
  • 平板端(≤992px):自动切换为每行6个,分成2行,卡片均匀占满容器宽度,无多余边缘间距
  • 移动端(≤576px):自动切换为每行4个,分成3行,同样贴合容器边缘
  • 所有屏幕尺寸下,卡片不会因未占满一行而增大边缘间距,空间不足时直接换行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 17:55:53