简体   繁体   中英

Reduce vertical space between 2 rows in a table HTML

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

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

First 1

Second 2

Third 3
Fourth 4

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

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 tr child using a combination of the :not() / :last-child pseudo classes.

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.

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:

在此输入图像描述

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

<table cellpadding=0 cellspacing=0>

and then set padding as desired, in CSS, on individual cells, eg with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM