如何仅拉伸CSS Grid中的某一个网格区域
问题描述
我有一个卡片位于高度大于卡片本身的grid行内,卡片高度设为100%,内部CSS Grid元素(.post-card a)也需100%高度。但为该元素设置height:100%时,所有网格行高度都会受影响。我希望仅最后一个网格区域.bottom-2填充外部网格单元格的剩余垂直空间,同时main网格区域保持.image设置的aspect-ratio,.title区域高度自适应内容。即保持当前代码片段的显示效果,仅让最后一行填充空白空间,该如何实现?
解决方案
要实现需求,核心是给内部网格容器设置100%高度,并通过grid-template-rows明确行高规则,让最后一行占据剩余空间:
- 给
.post-card a添加height:100%,确保它完全填充父元素.post-card的高度 - 使用
grid-template-rows: auto auto 1fr定义行高:- 第一个
auto:对应main区域,高度由.image的aspect-ratio自动计算 - 第二个
auto:对应title区域,高度自适应内容 1fr:让.bottom-2区域占据所有剩余垂直空间
- 第一个
- 调整
grid-template-areas为三行结构,匹配行高设置
修改后的完整CSS代码
body > div + div{ margin-top: 2em; } .grid{ display: grid; height: 100vh; } .post-card{ border: 1px solid #000; height: 100%; } .post-card a{ display: grid; height: 100%; /* 占满父元素高度 */ grid-template-rows: auto auto 1fr; /* 定义行高规则 */ grid-template-areas: "main" "bottom-1" "bottom-2"; } .date{ grid-row: 1/2; grid-column: 1/2; width: fit-content; background-color: #000; color: #fff; /* 让文字可见 */ z-index:10; padding: 4px 8px; } .image{ grid-area: main; aspect-ratio: 16/3; background-color: #0e0; } .title{ grid-area: bottom-1; background-color: #0ee; padding: 8px; } .bottom-2{ grid-area: bottom-2; display: flex; align-items: center; /* 内容垂直居中 */ justify-content: space-between; /* 分散CTA和share */ background-color: #ee0; padding: 8px; } .share{ width: 30px; background-color: #e0e; display: flex; align-items: center; justify-content: center; }
HTML代码(保持不变)
<div class="grid"> <div class="post-card image-title-cta"> <a href="#"> <div class="date">date</div> <div class="image">image</div> <div class="title">title</div> <div class="bottom-2"> <div class="cta">cta</div> <div class="share">share</div> </div> </a> </div> </div>
效果说明
.image区域保持16/3的宽高比,不会被拉伸变形.title区域高度随内容自动调整,不会占用多余空间.bottom-2区域会自动填充外部网格单元格的剩余垂直空间,适配不同容器高度- 日期标签依然悬浮在图片上方,不影响其他区域布局
内容的提问来源于stack exchange,提问作者Luca Reghellin
相关产品推荐
相关产品推荐

