【问题标题】:How can I remove the spacing between these CSS rows?如何删除这些 CSS 行之间的间距?
【发布时间】:2021-08-23 16:48:48
【问题描述】:

我正在尝试使用 CSS 网格创建一个 article 组件。但正如您在下面看到的,articletitlepublicationexcerpt)内的不同元素之间存在大量垂直空间。

当我为行输入一个固定高度时(例如grid-template-rows: 10px 10px 10px),间距消失了,但只要我想使用更灵活的东西(autominmax),间距又回来了。

如何使用灵活的高度来消除垂直间距?

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>

【问题讨论】:

  • 你说的垂直间距有3
  • 我的意思是文章标题和出版物元信息之间的间距,以及出版物元信息和摘录之间的间距
  • 减少文章类中的填充。
  • 我想你忘记关闭css中的.publication标签。
  • .title h2 中删除margin-block-end。代码将是.title h2 { margin-block-end: 0; }

标签: html css css-grid


【解决方案1】:

尝试在你的 CSS 顶部添加这个 -

*,*:after,*:before{
  padding:0;
  margin:0;
  box-sizing: border-box;
}

它将重置浏览器的默认内边距和边距,您可以在此处了解有关 box-sizing 的更多信息:https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing

代码笔:https://codepen.io/bilal-23/pen/YzQzKGx

【讨论】: