css grid 中 place-items 与 place-content 表现不同的核心原因在于它们作用的对象层级不同:前者控制网格容器内部各个单元格(grid items)在自身空间内的对齐方式,后者控制整个网格轨道(tracks)在容器剩余空间中的整体分布。简而言之,place-items 解决的是“子元素怎么放”的问题,而 place-content 解决的是“网格整体怎么摆”的问题。

place-items 如何影响单个单元格的对齐?
place-items 是 align-items 和 justify-items 的简写形式,它直接作用于网格容器内的每一个子元素。当网格单元格的尺寸大于其内容时,该属性决定了内容在单元格内部的垂直和水平对齐位置。例如,设置 place-items: center 会让所有子元素在各自的网格槽位中居中显示。如果未显式指定,默认值为 stretch,即子元素会拉伸以填满整个网格槽位的空间。

<div class="grid-container">
<div class="item">A</div>
<div class="item">B</div>
</div>
<style>
.grid-container {
display: grid;
grid-template-columns: repeat(2, 100px);
grid-template-rows: repeat(2, 100px);
/* place-items 控制每个 item 在其 100x100 槽位中的对齐 */
place-items: center;
}
.item {
width: 50px;
height: 50px;
background-color: lightblue;
}
</style>
在上述代码中,.grid-container 定义了一个 2x2 的网格,每个槽位大小为 100x100 像素。由于设置了 place-items: center,两个宽度为 50 像素的子元素 A 和 B 会在各自的槽位中水平和垂直居中。如果将 place-items 改为 start,子元素则会紧贴槽位的左上角。这种对齐行为仅发生在单元格内部,不影响网格轨道本身的布局结构。
place-content 如何控制网格整体的空间分布?
place-content 同样是 align-content 和 justify-content 的简写,但它作用于网格容器的整体空间分配。只有当网格的实际内容尺寸小于容器尺寸,或者网格轨道没有填满容器时,place-content 才会生效。它决定了所有网格轨道作为一个整体,在容器剩余空间中的排列方式。常见的值包括 center、space-between、space-around 等。如果网格已经填满了容器,place-content 的值将被忽略。
htmlq 是一个命令行工具,使用 CSS 选择器从 HTML 中提取内容,相当于 jq 的 HTML 版本。该工具使用 Rust 编写,允许你通过 CSS 选择器将 HTML 管道化,直接从终端提取文本、属性和结构化内容。

<div class="grid-container">
<div class="item">A</div>
<div class="item">B</div>
</div>
<style>
.grid-container {
display: grid;
width: 400px;
height: 400px;
grid-template-columns: 100px 100px;
grid-template-rows: 100px 100px;
/* place-content 控制整个 2x2 网格在 400x400 容器中的位置 */
place-content: center;
}
.item {
background-color: lightcoral;
}
</style>
在这个例子中,.grid-container 的尺寸为 400x400 像素,但定义的网格轨道总大小仅为 200x200 像素(两列各 100px,两行各 100px)。此时,容器内存在大量剩余空间。place-content: center 使得这 200x200 的网格区域在整个 400x400 容器中居中显示。如果设置为 space-between,则网格轨道会尽可能分散排列,首尾轨道分别贴靠容器的边缘。需要注意的是,如果网格轨道撑满了容器,即使设置了 place-content: space-around,也不会产生任何间距效果,因为已经没有多余空间可供分配。
当网格填满容器时 place-content 为何失效?
理解 place-content 失效的关键在于网格布局的计算顺序。CSS Grid 首先根据 grid-template-columns 和 grid-template-rows 确定轨道的大小,然后计算所有轨道的总尺寸。如果这个总尺寸大于或等于容器的可用空间,网格就会填满容器,此时不存在“剩余空间”,因此 place-content 没有任何操作对象。相比之下,place-items 始终有效,因为它处理的是每个单元格内部的内容对齐,无论单元格是否被拉伸。
<div class="grid-container">
<div class="item">A</div>
<div class="item">B</div>
<div class="item">C</div>
<div class="item">D</div>
</div>
<style>
.grid-container {
display: grid;
width: 200px;
height: 200px;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;
/* 网格自动填充容器,place-content 无效 */
place-content: space-between;
}
.item {
background-color: lightgreen;
}
</style>
在此代码中,.grid-container 为 200x200 像素,使用 1fr 单位定义了两列两行。四个子元素正好填满网格,轨道总尺寸等于容器尺寸。尽管设置了 place-content: space-between,但由于没有剩余空间,网格轨道之间不会产生间距,而是紧密排列填满容器。这验证了 place-content 仅在存在溢出或未填充空间时才起作用,而 place-items 则始终控制着每个子元素在其对应槽位内的对齐状态。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










