WillingLearner
WillingLearner

Reputation: 7316

Alternate rows in one column only - CSS

How do I color alternate rows in only one column in my table? What's the code for that?

Upvotes: 1

Views: 3036

Answers (4)

Russell Dias
Russell Dias

Reputation: 73292

As @afranz409 stated, the ideal solution would be to create a class. However, this can be done with a CSS specific solution, with limited browser capabilities (None of the IE browsers < 9):

table tr:nth-child(2n) > td:nth-child(1) {
    background-color: #eee;
}

In other words, for every alternate row, within the first table column, fill the background color #eee. As seen on JsFiddle.

For a more cross-browser compatible solution, I would recommend using this selector within jQuery:

$('table tr:nth-child(2n) > td:nth-child(1)').css("background-color", "#eee");

Upvotes: 4

Stephen Chung
Stephen Chung

Reputation: 14605

For the first column you can do something like:

tr:nth-child(odd) > td:first-child {
  background: green;
}
tr:nth-child(even) > td:first-child {
  background: blue;
}

It really depends on which column you want to color. If the x-th column, you can try td:nth-child(x).

Upvotes: 1

thirtydot
thirtydot

Reputation: 228162

You could do it using the nth-child() selector.

See: http://jsfiddle.net/thirtydot/2NxE6/

CSS:

tr:nth-child(2n) > td:nth-child(4) { /* highlight column 4 */
    background: #ccc
}

This works in modern browsers, but it doesn't work in Internet Explorer until version 9.

If you need it to work in earlier versions of Internet Explorer, here are your choices:

  • Use something like http://selectivizr.com/ to enable significant CSS3 support in older versions of IE.
  • Apply the selector using jQuery instead - this is a good option if your site already relies on jQuery.
  • Use another answer that suggests adding a class to the relevant td elements.

Upvotes: 2

afranz409
afranz409

Reputation: 772

You're going to have to set the class on the specific <td>'s that you want colored, rather than the <tr>'s like you would for alternating rows

Upvotes: 2

Related Questions