如何在Grid布局中对齐段落子元素?
如何在Grid布局中对齐段落子元素?
问题原因
你的三个section是网格容器的子项,但每个section内部是默认的块级布局:h1的高度会根据内容多少自动变化(比如有的标题是1行,有的是2行),再加上p的margin-top:1.5rem,就会导致不同section里的p起始位置错位,无法对齐。
解决方案:给section内部添加Grid布局
我们可以让每个section本身也成为一个Grid容器,把h1和p分配到独立的网格行中,这样不管h1的高度如何,所有p都会在各自section的第二行顶部开始,自然实现对齐。
修改后的CSS代码如下(重点标注了变化部分):
article#exhibition { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; & section { padding: 1rem; background-color: #61C9A8; /* 新增:让section成为Grid容器,划分两行 */ display: grid; grid-template-rows: auto 1fr; /* 用gap代替p的margin-top,更可控的间距 */ gap: 1.5rem; & a { font-weight: 400; /* 新增:让a不成为布局容器,h1和p直接作为section的Grid子项 */ display: contents; } & h1 { font-size: 2rem; color: #4C3B4D; } & p { /* 移除原来的margin-top,改用section的gap */ margin-top: 0; font-size: 1.5rem; /* 确保p在自己的网格行顶部对齐 */ align-self: start; } } }
关键修改点说明
- section内部Grid布局:
display: grid+grid-template-rows: auto 1fr把section分成两行:第一行自适应h1的高度,第二行占据剩余空间,p就固定在第二行的顶部。 - display: contents 给a标签:因为
a包裹了h1和p,默认会成为块级容器,打断section的Grid布局。用display: contents可以让a的子元素(h1、p)直接成为section的Grid子项,不影响布局结构。 - 用gap代替margin-top:相比
p的margin-top,section的gap能更稳定地控制h1和p之间的间距,不会因为h1高度变化产生偏移。
备选方案:Flex布局实现
如果你更习惯用Flex,也可以给section设置垂直方向的Flex布局,同样能实现对齐:
article#exhibition { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; & section { padding: 1rem; background-color: #61C9A8; /* 垂直方向的Flex容器 */ display: flex; flex-direction: column; gap: 1.5rem; & a { font-weight: 400; /* 让a成为Flex容器,继承section的垂直布局 */ display: flex; flex-direction: column; flex: 1; } & h1 { font-size: 2rem; color: #4C3B4D; /* 不让h1被压缩,保持原高度 */ flex-shrink: 0; } & p { margin-top: 0; font-size: 1.5rem; /* 固定p的起始位置,不被拉伸 */ flex-shrink: 0; } } }
两种方法都能解决你的对齐问题,Grid方案更直观地划分了布局区域,推荐优先使用。
内容来源于stack exchange
相关产品推荐
相关产品推荐

