FREELessons: 20Length: 1.2 hours

• Overview
• Transcript

6.2 Even and Odd Rows

When dealing with large tables it’s always a good idea to increase the readability by alternating the rows background color. For example, you could have a light gray background for the even rows and a while one for the odd rows.

In CSS, this is achieved through the nth-child selector.

7.Conclusion1 lesson, 01:47

6.2 Even and Odd Rows

When dealing with large tables, it's always a good idea to increase the readability by alternating the rows background color. For example, you could have a light grey background for the even rows, and a white one for the odd rows. Now, in CSS, this is achieved through the nth-child selector. So, let me show you a few examples. We have a simple table right here, and a simple list item. So, let's style this table a little bit at first. So, we can see the rows a little better. 2px solid, and a very light grey, like that. And then, we'll do that td and th. Again, border, 1px solid, same color. And let's do a padding of 1em. Okay, something like that and finally, on the th, on the table headings, we'll align the text to the left. Okay, just like that. Now, let's say we wanna color the even rows. To do that, you'll go to tr, which is the table row. And you would say, nth-child(even). And then you just change the background-color, something like this. Save, and there it is. Now, this is colored and this is colored. If you change this to odd. It will color one, three, five, and so on. Now, you can have even more control on that by using a slightly different technique. For example, list item. So, we're talking about the list right now, nth-child and we'll do this 2n. Let's change the color to blue, and see what happens. Well, 2n is equal to even. So 2, 4, 6, and so on are colored. If I change this to even, it's the exact result. If I change this to 3n, it's gonna color the third, the sixth, every third item. The same goes for like 4n, 5n, and so on. You can even do this, +4 or +5. That means, it's gonna color the fourth element starting with the fifth element. So, you can see, it starts from 5, and then the fourth element from the fifth element is Item 9. And so, let me give you another example. Like, if you want to start from the second element, yeah, you have Item 2, and then Item 6, Item 10, and so on. Now, keep in mind, this is a CSS3 selector, so it will not work in IE8. Other than that, it's supported in all major browsers.

Back to the top