Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 857
user2480288 Avatar asked Sep 18 '13 19:09

user2480288


2 Answers

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:

enter image description here

like image 178
Josh Crozier Avatar answered Sep 30 '22 13:09

Josh Crozier


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, e.g. with

tr:not(:last-child) td { padding-top: 4px }
like image 25
Jukka K. Korpela Avatar answered Sep 30 '22 12:09

Jukka K. Korpela