减少表格 HTML 中两行之间的垂直空间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18880947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:33:27  来源:igfitidea点击:

Reduce vertical space between 2 rows in a table HTML

htmlcsshtml-table

提问by user2480288

I have a table with multiple rows, for example five rows. I need to reduce the gap between the third and fourth rows.

我有一个多行的表,例如五行。我需要减少第三行和第四行之间的差距。

Below is my code:

下面是我的代码:

<table>
    <tr>
        <td>First Row</td>
        <td>1</td>
    </tr>
    <tr>
        <td>Second Row</td>
        <td>2</td>
    </tr>
    <tr>
        <td>Third Row</td>
        <td>3</td>
    </tr>
    <tr>
        <td>Fourth Row</td>
        <td>4</td>
    </tr>

The result is

结果是

First 1

Second 2

Third 3

Fourth 4

前 1

第二个2

第三个3

第四 4

I want to remove the gap between the third and fourth rows as below:

我想消除第三行和第四行之间的差距,如下所示:

First 1

Second 2

Third 3
Fourth 4

前 1

第二个2

第三 3
第四 4

Is it possible to set the padding between third and fourth row only to 0? to reduce the gap between them?

是否可以将第三行和第四行之间的填充设置为 0?缩小他们之间的差距?

回答by Josh Crozier

It's worth noting that the space can be reduced by collapsing the table's borders:

值得注意的是,可以通过折叠表格的边框来减少空间:

table {
    border-collapse: collapse;
}

You could do something similar to what Jukka K. Korpela suggests, and set padding on all the elements except the last trchild using a combination of the :not()/:last-childpseudo classes.

您可以执行类似于 Jukka K. Korpela建议的操作,并tr使用:not()/:last-child伪类的组合在除最后一个子元素之外的所有元素上设置填充。

EXAMPLE HERE

示例在这里

tr:not(:last-child) td {
    padding-top: 1em;
}

The above example works in your instance, however the targeted element may not be the last element. You could therefore use the :nth-child()pseudo class to target the desired element.

上面的示例适用于您的实例,但是目标元素可能不是最后一个元素。因此,您可以使用:nth-child()伪类来定位所需的元素。

EXAMPLE HERE

示例在这里

tr td {
    padding-top: 1em;
}
tr:nth-child(4) td {
    padding-top: 0;
}

As you can see, this approach works when you have more elements:

如您所见,当您有更多元素时,此方法有效:

enter image description here

在此处输入图片说明

回答by Jukka K. Korpela

Unless you use special settings in HTML, there will be just a couple of pixels between rows of a table. If you really want to remove that, the simplest way is to use

除非您在 HTML 中使用特殊设置,否则表格的行之间将只有几个像素。如果你真的想删除它,最简单的方法是使用

<table cellpadding=0 cellspacing=0>

and then set padding as desired, in CSS, on individual cells, e.g. with

然后根据需要设置填充,在 CSS 中,在单个单元格上,例如

tr:not(:last-child) td { padding-top: 4px }