Create html table and zebra it

Question:

I would like to know, how do I zebraze an HTML table? It has only two columns and the information is dynamically populated from the controller and the DB.

Answer:

The nth-child pseudo-class selects elements from a tree of elements referring to their specific position. You can for example select the odd or even elements.

tr:nth-child(2n+2) {
    background: #ccc;
}

The calculation used by nth-child is quite simple. You will most often use sum. Remember? The formula will be as follows: an+b.

Here's how it works: the browser applies the style every 2 tr.

You can facilitate, using the words odd or even, to select the odd or even elements of the tree.

tr:nth-child(odd) {
    background: #ccc;
}

If the value of a (an+b) is equal to 0, you don't need to put the formula, just the number referring to the order of the element. Example:

table tbody tr:nth-child(1) {
    background: #ccc;
}

source: CSS property: nth-child
Working example: jsfiddle

This selector is compatible with the following browsers:

Desktop

  • Chrome – 1.0
  • Firefox (Gecko) – 3.5 (1.9.1)
  • Internet Explorer – 9.0
  • Opera – 9.5
  • Safari – 3.1

mobile

  • Android – 2.1
  • Firefox Mobile (Gecko) – 1.0 (1.9.1)
  • IE Mobile – 9.0
  • Opera Mobile – 9.5
  • Safari Mobile – 3.1
Scroll to Top