CSS Grid间隙异常:设置1px间隙却出现2px间隙问题排查
CSS Grid 间隙异常问题排查
我编写了如下使用CSS Grid的HTML文档:
<!DOCTYPE html> <html lang="en-IT"> <head> <title>Site</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> .grid1 { display: grid; grid-template-columns: repeat(3, 1rem); grid-template-rows: repeat(3, 1rem); row-gap: 1px; column-gap: 1px; } .cell1 { fill:rgb(130, 190, 234); stroke-width:0; stroke:rgb(0,0,0); width: 100%; height: 100%; } </style> </head> <body id="mainBody"> <div class="grid1"> <svg height="100%" width="100%" xmlns="http://www.w3.org/2000/svg"> <rect class="cell1"/> </svg> <svg height="100%" width="100%" xmlns="http://www.w3.org/2000/svg"> <rect class="cell1"/> </svg> <svg height="100%" width="100%" xmlns="http://www.w3.org/2000/svg"> <rect class="cell1"/> </svg> <svg height="100%" width="100%" xmlns="http://www.w3.org/2000/svg"> <rect class="cell1"/> </svg> <svg height="100%" width="100%" xmlns="http://www.w3.org/2000/svg"> <rect class="cell1"/> </svg> <svg height="100%" width="100%" xmlns="http://www.w3.org/2000/svg"> <rect class="cell1"/> </svg> <svg height="100%" width="100%" xmlns="http://www.w3.org/2000/svg"> <rect class="cell1"/> </svg> <svg height="100%" width="100%" xmlns="http://www.w3.org/2000/svg"> <rect class="cell1"/> </svg> <svg height="100%" width="100%" xmlns="http://www.w3.org/2000/svg"> <rect class="cell1"/> </svg> </div> </body> </html>
尽管我将row-gap和column-gap都设置为1px,但实际显示却出现异常:
可以看到,第一列和第一行的间隙宽度为2px,增加行列数量后该模式会重复。请问哪里操作出错了?
问题原因与解决方法
问题出在SVG元素的默认外边距上。浏览器会给SVG元素添加默认的margin(通常是4px左右),这些额外的外边距和Grid设置的gap叠加,就造成了看起来间隙变宽的效果。
快速修复方案
给SVG元素重置外边距即可:
.grid1 svg { margin: 0; }
更简洁的替代方案
其实没必要每个单元格都嵌套SVG,直接用div配合背景色就能实现相同效果,还能避免SVG的默认样式问题:
<!DOCTYPE html> <html lang="en-IT"> <head> <title>Site</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> .grid1 { display: grid; grid-template-columns: repeat(3, 1rem); grid-template-rows: repeat(3, 1rem); gap: 1px; /* 合并row-gap和column-gap的写法 */ } .cell1 { background-color: rgb(130, 190, 234); } </style> </head> <body id="mainBody"> <div class="grid1"> <div class="cell1"></div> <div class="cell1"></div> <div class="cell1"></div> <div class="cell1"></div> <div class="cell1"></div> <div class="cell1"></div> <div class="cell1"></div> <div class="cell1"></div> <div class="cell1"></div> </div> </body> </html>
内容的提问来源于stack exchange,提问作者Frax
相关产品推荐
相关产品推荐

