justify-items控制网格项行内轴(水平)对齐,align-items控制块轴(垂直)对齐;均作用于容器,可被justify-self/align-self覆盖;取值为start/end/center/stretch/baseline;place-items是其简写,语法为place-items: 。

grid-container 的 justify-items 和 align-items 怎么用
justify-items 控制所有网格项在**行内轴(inline axis)**上的对齐,也就是水平方向(左/中/右);align-items 控制**块轴(block axis)**上的对齐,即垂直方向(上/中/下)。两者作用于整个容器,影响所有子项,但会被单个网格项的 justify-self 或 align-self 覆盖。
常见取值都一样:start、end、center、stretch(默认)、baseline。注意:stretch 会让项目拉伸填满单元格,如果项目本身有固定宽高或 max-width/max-height,就可能不生效。
-
justify-items: center让所有项目在列方向居中(水平居中),但前提是列轨道有足够剩余空间 - 如果某列设了
grid-template-columns: 100px 1fr,第二列会撑开,第一列里项目居中才明显可见 -
align-items: start不等于“顶对齐”——它对齐的是单元格的 block-start 边界,在从上到下书写流中才是顶部
单个网格项用 justify-self / align-self 覆盖全局对齐
当某个按钮需要右对齐,而其他按钮居中时,不能靠改容器属性,得直接在该 这两个属性优先级高于容器的 立即学习“前端免费学习笔记(深入)”; 例如: 当网格容器有**多行或多列轨道**,且总尺寸大于所有轨道之和时,多余空间由 比如 justify-self:
.cta-button {
justify-self: end;
align-self: center;
}
justify-items 和 align-items,且可单独设置。它们也支持 self-start、self-end 等相对自身书写模式的值,但多数场景用 start/end 更可控。
width 或 min-width,justify-self: stretch 就不会拉宽它align-self: baseline 在含文本的项目间对齐效果好,但需注意父容器 align-items 不能是 stretch,否则 baseline 对齐会被覆盖self-start 这种写法,Grid 里这个细节容易被忽略place-items 是 justify-items + align-items 的简写,但有陷阱
place-items 是双值简写,语法为 place-items: (注意:先 align,后 justify,和 flex 的 place-content 顺序不同)。place-items: center 等价于 align-items: center; justify-items: center;place-items: end start 表示垂直靠下、水平靠左。
place-items: start end 是“左对齐+右对齐”,实际是“上对齐+水平右对齐”place-content 那样控制整个网格区域的对齐(那是针对空隙的),place-items 只管项目本身align-content / justify-content 控制的是网格线之间的空隙,不是项目
align-content(块轴)和 justify-content(行内轴)分配。它们对齐的是**轨道组(track group)**,不是单个项目。grid-template-rows: repeat(3, 50px),容器高 300px,但设了 height: 400px,多出的 100px 就由 align-content 分配。
对齐行为是否生效,关键看有没有「可分配的剩余空间」——容器尺寸、轨道定义、项目尺寸三者共同决定。很多“没反应”的情况,其实是轨道已占满容器,或者项目本身限制了拉伸。align-content: space-between 把行轨道首尾撑到容器边缘,中间均分空隙grid-template-rows: 50px),align-content 完全无效——这点常被当成 bug,其实是设计如此align-items 控制;即使 align-content: end 把整行轨道压到底部,项目在单元格里还是按 align-items 对齐










