Create html table and zebra the same

6

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

    
asked by anonymous 07.05.2014 / 19:30

3 answers

10

The nth-child pseudo-class selects elements from a tree of elements referring to the specific position of each. You can, for example, select 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 soma. Remember? The formula will be as follows: an + b.

The operation is as follows: the browser applies the style every 2 tr.

You can use odd or even words to select the odd or even elements of the tree.

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

If the value of a (an + b) equals 0, you do not need to put the formula, just the number for the order of the element. Example:

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

source: CSS property: nth-child
Example working: 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
07.05.2014 / 19:37
4

You have a few options. With CSS 3 you can use nth-child(even) and nth-child(odd) to reference the odd and even rows and the cells within those rows. Then you would have the style for tr:nth-child(even) and similarly for odd . See about it here .

Another solution is using jQuery: you can use the above constructs in jQuery to select the elements. Basically you would select $("table tr:nth-child(even)") and analog for odd as well.

The solution with CSS 3 is more interesting (in my opinion) for maintaining the style of the site / app in CSS. The problem is that it will not work on older browsers that do not support the feature. In such cases, if it is a requirement to support older browsers the jQuery solution might be more interesting.

    
07.05.2014 / 19:38
1

An alternative and using jquery in your project you can use this way

function zebrar() {
    $('table th').css('background-color', 'green');
    $('table tbody tr:even').css('background-color', '#efe3e');
    $('table tbody tr:odd').css('background-color', 'silver');
}

simple and practical

    
07.11.2014 / 17:55