使用CSS grid实现article组件时如何消除行间的多余垂直间距?
问题
我尝试使用CSS grid创建article组件,如下方示例所示,article内部的title、publication和excerpt不同元素之间存在大量垂直间距。
当我为行设置固定高度(例如grid-template-rows: 10px 10px 10px)时,间距会消失,但只要我使用更灵活的配置(auto或minmax),间距就会再次出现。
我该如何在使用灵活高度的同时消除这些垂直间距?
相关代码如下:
main { display: flex; flex-direction: column; width: 500px; margin: 0 auto; } .article { border-top: 1px solid #FF0000; border-bottom: 1px solid #FF0000; display: grid; grid-template-rows: auto auto auto; padding: 10px 30px; color: #414a4c; } .publication { display: flex; justify-content: space-between; color: #757575; }
<main> <a href="#" class="article"> <div class="title"> <h2>Article title number 1</h2> </div> <div class="publication"> <h4>The Guardian</h4> <h4>27 May 2021</h4> </div> <div class="exerpt"> <p>This is an excerpt from the article this is an excerpt from the article, etc, etc.</p> </div> </a> <a href="#" class="article"> <div class="title"> <h2>Article title number 2</h2> </div> <div class="publication"> <h4>The Intercept</h4> <h4>27 May 2021</h4> </div> <div class="exerpt"> <p>This is an excerpt from the article this is an excerpt from the article, etc, etc.</p> </div> </a> <a href="#" class="article"> <div class="title"> <h2>Article title number 3</h2> </div> <div class="publication"> <h4>Yes Magazine</h4> <h4>27 May 2021</h4> </div> <div class="exerpt"> <p>This is an excerpt from the article this is an excerpt from the article, etc, etc.</p> </div> </a> </main>
解决方案
你观察到的间距和Grid布局本身无关,是浏览器给<h2>、<h4>、<p>这类标签默认添加的上下外边距导致的。
设置固定行高时,行高限制了元素区域的总高度,默认外边距被压缩所以看不到间距;使用auto或者minmax灵活配置时,Grid行高会自动包含元素本身高度加默认外边距,间距就会显现。
只要重置掉这些标签的默认外边距即可解决问题,添加以下CSS:
/* 按需可以保留合适的边距数值,这里直接清零 */ h2, h4, p { margin: 0; }
如果需要自定义元素之间的垂直间距,可以给.article添加row-gap属性精准控制,示例:
.article { /* 原有属性保持不变,新增下面这行,数值可按需调整 */ row-gap: 8px; }
这样既保留了高度的灵活性,也能自由控制间距大小。
内容的提问来源于stack exchange,提问作者krimo33
相关产品推荐
相关产品推荐

