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.
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.
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
Desktop
Mobile
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.
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