添加align-items:center后Grid边框失效,求解决方法
修复Grid布局中
align-items: center导致的边框异常问题 问题背景
为让带有超长描述的行里的Link 2实现垂直居中,我给.tableRow添加了align-items: center属性,结果直接导致Grid布局的边框出现错位异常。
原始代码
CSS
table { border: 1px solid #000; border-collapse: collapse; } a { color: red; } .tableRow { position: relative; display: grid; text-decoration: none; color: inherit; grid-template-columns: repeat(2, 1fr); /* place-items: center; */ border: 1px solid #000; border-bottom: none; align-items: center; } .tableRow:hover, .tableRow:focus { background: #eee; outline: none; } .tableRow:last-child { border-bottom: 1px solid #000; } .tableRow a:not(.tableRowLink) { position: relative; z-index: 1; } .tableCell { padding: 18px; border-right: 1px solid #000; } .tableCell:last-of-type { border-right: none; } .tableRowLink { position: absolute; top: 0; left: 0; right: 0; bottom: 0; }
HTML
<div class="table"> <div class="tableRow"> <div class="tableCell"><a href="https://www.apple.com/" target="_blank"><p>Link 1</p></a></div> <div class="tableCell"><p>Short Description</p></div> <a class="tableRowLink" href="https://www.apple.com/" target="_blank"></a> </div> <div class="tableRow"> <div class="tableCell"><a href="https://www.google.com/" target="_blank"><p>Link 2</p></a></div> <div class="tableCell"><p>Very Long Description Very Long Description Very Long Description Very Long Description Very Long Description Very Long Description Very Long Description Very Long Description Very Long Description</p></div> <a class="tableRowLink" href="https://www.google.com/" target="_blank"></a> </div> </div>
问题原因
align-items: center作用在Grid容器(.tableRow)上时,会让所有Grid子项(.tableCell)在交叉轴上居中对齐,这会导致内容较少的单元格高度不再自适应拉伸至行高,而是收缩到内容高度,最终造成边框错位。
修复方案
移除Grid容器上的align-items: center,转而给单元格内部内容设置垂直居中样式:
修改后的CSS
table { border: 1px solid #000; border-collapse: collapse; } a { color: red; } .tableRow { position: relative; display: grid; text-decoration: none; color: inherit; grid-template-columns: repeat(2, 1fr); border: 1px solid #000; border-bottom: none; /* 移除原有的align-items: center */ } .tableRow:hover, .tableRow:focus { background: #eee; outline: none; } .tableRow:last-child { border-bottom: 1px solid #000; } .tableRow a:not(.tableRowLink) { position: relative; z-index: 1; } .tableCell { padding: 18px; border-right: 1px solid #000; /* 添加以下样式实现内容垂直居中 */ display: flex; align-items: center; min-height: 100%; } .tableCell:last-of-type { border-right: none; } .tableRowLink { position: absolute; top: 0; left: 0; right: 0; bottom: 0; }
方案说明
- 移除
.tableRow的align-items: center,让Grid单元格高度自适应行内最高内容的高度 - 给
.tableCell添加display: flex; align-items: center;,让单元格内部的文本/链接垂直居中 min-height: 100%确保单元格高度不会低于行高,保证边框完全对齐
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

