Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Css coloring table problem

I've been trying to make a colored table with even rows a different color than the odd ones. The only problem I have is that I have to be able to do it even with hidden rows, because if for instance you hide row 2 then you see row 1 and row 3 the same color.

Here's what I have:

tr:not([display="none"]):nth-child(even){
    background: #EFEFFF;
}
tr:not([display="none"]):nth-child(odd){
    background: #E0E0FF;
}

This code doesn't work for me since browsers don't filter :not and :nth-child according to the given order. Any suggestions?

like image 206
Gonzalo Avatar asked Aug 14 '11 03:08

Gonzalo


People also ask

How do I change the background color of a table in CSS?

The background color of the table is given by the bgcolor="color" attribute. When applied to the <table> tag, the color fills the background. Cell background colors are set by applying the bgcolor attribute to a <tr> tag (to color the row) or to a <td> tag (to color the cell).

How do I make rows alternate color in CSS?

A style selector in CSS is used to change the alternative rows. Using the CSS style selector, you can easily modify the color of the alternate rows. The nth-child() selector in CSS takes an even or odd parameter and then changes the color using the background-color property within this style selector.

How do I change the color of a row in a table?

Using pre-defined classes, we can change the color of table cells and table rows. In order to change the color of the table row, we need to specify in <tr> tag with the required class & for changing the color of the table row then specify it inside <td> tag with the required class.


2 Answers

Could you add a class to the visible rows so you could write it as:

tr.visible:nth-child(even) {
    background: #EFEFFF;
}
tr.visible:nth-child(odd){
    background: #E0E0FF;
}

Then use jquery to add/remove the class as you make rows visible/invisible?

like image 178
boatcoder Avatar answered Sep 28 '22 02:09

boatcoder


Ended up here while trying to tackle a similar problem. Used the following JS to update the CSS based on an added class after filtering.

$('tr.visible').filter(':odd').css('background-color', '#EFEFFF');
$('tr.visible').filter(':even').css('background-color', '#E0E0FF');

Note the flipped colors due to zero indexed arrays.

like image 29
Jason Tucker Avatar answered Sep 28 '22 02:09

Jason Tucker