user11343394
user11343394

Reputation: 63

how to put a line under first row in table

I'm trying to put a line under the first row in my table but its not working. I followed the w3 schools guide for tables but it doesnt show how to put lines. I tried to put a border on the th, but it leaves a gap in the line. when I try to put a border on the tr, it doesnt work.

Here is my code:

tr {
  border-style: solid;
  border-width: 2px;
  border-color: black;
}
<table>
  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td>80</td>
  </tr>
</table>

Upvotes: 4

Views: 3215

Answers (4)

Nick
Nick

Reputation: 1422

Tables are only meant to be formatted via individual cells. If you try to style a tr tag, you need to make sure you have border-collapse: collapse on your table. To target just the first tr specifically, set your specifier as tr:first-of-type and add a border-bottom: 2px solid black.

table {
  border-collapse: collapse;
}

tr:first-of-type {
  border-bottom: 2px solid black;
}
<table>
  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td>80</td>
  </tr>
</table>

Upvotes: 5

Mario Mucalo
Mario Mucalo

Reputation: 635

Check here:

Add border-bottom to table row <tr>

element is not the best place to define the border. You should define the border of the or elements inside.

So, give your tr element a class:

<tr class="myClass">

and then define it in the CSS like this:

tr.myClass td, tr.myClass th {
    border-bottom: 1px solid black;
}

If you are annoyed by the line not being continuous, make sure you set the cellspacing on your table to 0:

<table cellspacing="0">

Cheers!

Upvotes: 0

Upamanyu Sundaram
Upamanyu Sundaram

Reputation: 149

Add this to your styles

tr:first-child th {
    border-bottom: solid 1px black;
}

What you're doing is selecting the "th" cells in a tables row if that row is the first child of its parent. And then you're applying the specified style.

Upvotes: 0

Vsevolod Fedorov
Vsevolod Fedorov

Reputation: 521

You can try collapse borders table and after that set border to you th

tr th{
  border-bottom:2px solid #000;
}
table {
  border-collapse: collapse
}
<table>
  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td>80</td>
  </tr>
</table>

Upvotes: 5

Related Questions