Styling Table Rows
In this guide you'll learn how to style table rows, including using the nth child selectors to dynamically style alternating rows.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

To continue with our table styles, we're going to style the table rows and headers in this video.

Let's create styling attributes for our <td> and <th> rows. Though we did styling for <th> row earlier, we are going to style the elements inside each cell, so they're applicable to the entire table.

Let's start with a padding of 15px. Next, our items are not lined up properly, so we'll fix that with the attribute text-align that'll take the value left.

This gives us a much better-looking table.

large

Lastly, we'll add a border that is 1px thick, solid and is grey in color. The code is:

td, th {
  padding: 15px;
  text-align: left;
  border: 1px solid grey;
}

I want to show you an important thing here. Say, we give a background-color of red, it'll override the style of <th> tag, that we defined earlier. This is how CSS works, as the last tag will take precedence over the earlier styles. It's good to be familiar with this behavior.

th {
  background-color: black;
  color: white;
}

td, th {
  padding: 15px;
  text-align: left;
  border: 1px solid grey;
  background-color: red;
}

The output would be:

large

To overcome this behavior, we're going to use a pseudo element called tr-nth-child(). This tag will help us select a particular item. If you see, this tag works like a function, so we can pass a specific row as its parameter. In this case, I'm going to pass the word even to this function, so it'll apply this style only for the even rows. This is the best way to implement alternate styles for every row, something you'll see commonly in many sites. Here, I'm going to give a background color of brown and a text color of white.

The code is:

tr:nth-child(even)  {
  background-color: brown;
  color: white;
}

and the output is:

large

This way, the earlier style of <th> is maintained, and at the same time, the different tables have a dynamic color.

One thing to keep in mind is our table header is the first row, and this is why CSS skips applying the new style to this row.

Also, there is a significant difference based on the order. <th> is more specific as it applies to a particular element inside a row, whereas <tr> is less specific as it applies to the entire row. This is why the style in <th> takes precedence.

I think this is pretty cool!