Gaddafi Rusli
Gaddafi Rusli

Reputation: 320

How to target the <td>'s that falls under <th> with a colspan?

I have a dynamic table that generally look like this

----------------------------------------------------
|       AA        |      BB     |       CC        |
----------------------------------------------------
| X1 |  X2  | X3  |  Y1  |  Y2  |  Z1  | Z2  | Z3 |
----------------------------------------------------
| xx |  xx  | xx  |  yy  |  yy  |  zz  | zz  | zz |
---------------------------------------------------- 
| xx |  xx  | xx  |  yy  |  yy  |  zz  | zz  | zz |
---------------------------------------------------- 

And I want to have different colors for AA, BB, CC, etc - generally alternate color (zebra stripes). I don't want to target just the AA cell, but the all the columns that fall under AA cell. All the <td>s under it.

I can't target using the the :nth-child(odd) because it will select the odd child columns instead of the odd column of <th> elements, and its childs.

Note that the number of child columns is not fixed. it can be one, two, three or more.

Is there any way I can achieve that?

Upvotes: 1

Views: 132

Answers (2)

G-Cyrillus
G-Cyrillus

Reputation: 105913

I see two CSS option to have something fluid.

1) (clumsy and tricky) for just a color , you may repeat a box-shadow under th. http://codepen.io/anon/pen/ysLvE

th:nth-child(even) {
  background:yellow;
  box-shadow:
    0 1em  0  yellow,
    0 3em  0  yellow,
 /* and so on as much as needed , here Sass or alike is your friend */
    0 29em 0  yellow
}

here a Sass/scss version : http://codepen.io/gc-nomade/pen/xqALu

2) (a bit smarter) you may insert a pseudo element with a background-image http://codepen.io/anon/pen/EgCJp

th:after {
  content:'';
  display:block;
  height:3000px;/* what you think long enough */
  margin-bottom:-3000px; /* negative margin to reduce height virtually to zero */
  background:yellow url(http://lorempixel.com/600/800/nature/1) center;
}

If these approach do not suit your way of using CSS , javascript will then, be your savior :). ++

Upvotes: 1

peterh
peterh

Reputation: 1

It is possible with pure css, although requires css3 and it is not really beautiful:

TABLE > TH > TD:nth-child(1),
TABLE > TR > TD:nth-child(1),
TABLE > TR > TD:nth-child(2),
TABLE > TR > TD:nth-child(3) {
    background-color: red;
}

Second, third, columns go the same way.

It can be a little bit better if you can give the needed td-s a common class name (f.e. "redColumn" and "greenColumn"). In this case a simple

.redColumn {
    background-color: red;
}

.greenColumn {
    background-color: green;
}

will be ok.

Upvotes: 0

Related Questions