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

CSS Grid中图片无法居中问题求助(Codecademy项目)

解决CSS Grid中图片居中的问题

你的问题主要出在两个地方:网格区域未正确绑定,以及图片的居中逻辑没作用到正确的容器上,下面是具体的修复方案:

问题分析

  1. 你定义了grid-template-areas,但没有给每个.img-*元素设置对应的grid-area属性,导致网格布局并未按照你预期的2x2结构排列。
  2. justify-items:center是作用于Grid容器,控制网格项在单元格内的对齐,但.img-*是块级元素,默认会占满整个单元格宽度,所以这个属性无法影响内部的图片;你需要让图片在自己的父容器(.img-*)内居中。

修复后的代码

CSS部分

/* Services */

.services-title {
  text-align: center;
  margin-bottom: 0;
}

.services {
  display: flex;
  justify-content: center; /* 让整个网格容器在页面水平居中 */
}

.image-container {
  display: grid;
  grid-template-areas: 'img-1 img-2' 'img-3 img-4';
  grid-template-columns: 1fr 1fr; /* 让两列宽度均等 */
  gap: 1%; /* 用gap代替margin,更符合Grid布局规范 */
  padding: .5rem;
}

/* 绑定网格区域与对应元素 */
.img-1 { grid-area: img-1; }
.img-2 { grid-area: img-2; }
.img-3 { grid-area: img-3; }
.img-4 { grid-area: img-4; }

.image-container h3 {
  background-color: #c4a77d;
  color: #313715;
  font-size: 1.45rem;
  text-align: center; /* 让标题也居中 */
  margin: 0;
  padding: 1rem 0;
}

.img-1,
.img-2,
.img-3,
.img-4 {
  background-color: #c4a77d;
  opacity: .75;
  text-align: center; /* 关键:让内部图片和标题水平居中 */
}

.services img {
  border: 2px solid #313715;
  border-radius: 5px;
  width: 90%;
  margin: 1rem 0; /* 给图片添加上下间距,提升美观度 */
}

.services h2 {
  text-align: center;
}

HTML部分(无需修改)

<h2 class="services-title">Our Services</h2>
<div class="services" id="services">
  <div class="image-container">
    <div class="img-1">
      <h3>Herbal Mixes</h3>
      <img src="img-1" alt="alt">
    </div>
    <div class="img-2">
      <h3>Spelled Candles</h3>
      <img src="img-2" alt="alt">
    </div>
    <div class="img-3">
      <h3>Herbal Tinctures</h3>
      <img src="img-3" alt="alt">
    </div>
    <div class="img-4">
      <h3>Organic Herbs</h3>
      <img src="img-4" alt="alt">
    </div>
  </div>
</div>

关键修改点说明

  • 给每个.img-*添加grid-area属性,与grid-template-areas定义的区域名对应,确保网格布局正确生效。
  • 在.services容器中添加justify-content:center,让整个网格模块在页面水平居中。
  • 给.img-*设置text-align:center,因为图片是行内块元素,这个属性可以直接让它在父容器内水平居中;如果更倾向于flex布局,也可以把.img-*设置为display:flex; flex-direction:column; align-items:center;,效果一致。
  • 用gap替代.img-*的margin,这是Grid布局中控制网格项间距的标准做法,避免margin带来的布局偏移问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 14:12:17