
本文详解如何使用 css grid 构建一个双栏布局:左侧为垂直水平均居中的标题与描述文本,右侧为完整填充网格区域、不拉伸不裁剪的响应式图像,并统一置于纯色背景面板中。
本文详解如何使用 css grid 构建一个双栏布局:左侧为垂直水平均居中的标题与描述文本,右侧为完整填充网格区域、不拉伸不裁剪的响应式图像,并统一置于纯色背景面板中。
在现代网页布局中,CSS Grid 是实现精准、灵活双栏结构的首选方案。但初学者常遇到两个典型问题:文本无法在网格单元内真正居中(仅靠 text-align 不够),以及图像无法自然填满右侧网格区域,反而被拉伸或裁剪。根本原因在于:Grid 容器默认采用 align-items: stretch(子项纵向拉伸),且图像作为替换元素,其尺寸受 max-width/max-height 与父容器约束共同影响,缺少显式宽高定义时行为不可控。
下面是一套经过验证的、语义清晰且可复用的解决方案:
✅ 正确的 HTML 结构(保持语义化)
<div class="colored-panel">
<div class="grid-container">
<div class="text">
<h1>Welcome to my website!</h1>
<p>A concise description goes here.</p>
</div>
<div class="apu-img">
<img class="apu-image"
src="pics/apu.jpg"
alt="Portrait of Apu Siqay">
</div>
</div>
</div>✅ 关键 CSS 解析与优化
.colored-panel {
background-color: #6A1A2F;
padding: 20px;
color: #333;
/* 移除固定 height,改用 min-height 保证内容适配 */
min-height: 460px;
}
.grid-container {
display: grid;
/* 推荐写法:更健壮的 1:1 分栏(兼容小屏)*/
grid-template-columns: repeat(2, minmax(0, 1fr)));
gap: 20px; /* 替代已废弃的 grid-gap */
color: white;
/* 核心修复①:使所有直接子项在交叉轴(垂直方向)居中 */
align-items: center;
/* 可选:如需文字/图像在各自格子内也水平居中,加此行 */
justify-items: center;
}
.text h1 {
margin: 0;
font-size: 60px;
line-height: 1.2;
}
.text p {
margin: 16px 0 0;
font-size: 18px;
opacity: 0.9;
}
.apu-img {
/* 确保图像容器不溢出、不塌陷 */
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.apu-image {
/* 核心修复②:三重保障图像表现 */
width: 100%;
height: 100%;
object-fit: contain; /* 或 use 'cover' if you prefer full coverage with cropping */
object-position: center;
max-width: none; /* 覆盖可能的全局 img 重置样式 */
}? 关键要点说明
- align-items: center 是垂直居中的核心:它作用于 Grid 容器,让 .text 和 .apu-img 两个网格项在纵向上对齐居中——这解决了“文本卡在顶部”和“图像下坠”的问题。
-
图像必须设置 width: 100%; height: 100%:仅靠 max-width: 100% 无法强制图像撑满父容器;显式宽高 + object-fit 才能精准控制渲染效果:
- object-fit: contain → 等比缩放,完整显示,留白可接受;
- object-fit: cover → 等比缩放并裁剪,完全填满,适合强调视觉冲击。
- 避免固定 height 在 .colored-panel 上:它会破坏响应性;改用 min-height 并配合 padding,确保内容始终有足够空间。
- 慎用 text-align: center 在容器上:它只影响内联级内容(如文字、图片),对块级网格项无效;居中逻辑应由 Grid 自身属性(align-items / justify-items)接管。
? 进阶提示(响应式增强)
如需在移动端堆叠显示(单列),可添加媒体查询:
立即学习“前端免费学习笔记(深入)”;
@media (max-width: 768px) {
.grid-container {
grid-template-columns: 1fr;
text-align: center;
}
.apu-img {
order: -1; /* 图像移到文字上方 */
}
}这套方案兼顾可维护性、可访问性与视觉一致性,无需 JavaScript,纯 CSS 即可交付专业级布局效果。掌握 align-items、object-fit 和 minmax() 的组合运用,是驾驭现代 CSS 布局的关键一步。

















