<table>
<tr>
<th>heading a</th>
<th>heading b</th>
<th>heading c</th>
</tr>
<tbody>
<tr>
<td>Blue</td>
<td>data 2</td>
<td>data 3</td>
<td>data 4</td>
</tr>
<tr>
<td>White</td>
<td>data 2</td>
<td>data 3</td>
<td>data 4</td>
</tr>
<tr>
<td>Blue</td>
<td>data 2</td>
<td>data 3</td>
<td>data 4</td>
</tr>
</tbody>
</table>
above is a sample table for this question. So, first to give some context I want to create a table with a frozen first column. I have done that by selecting the first child td of tr and setting the position as absolute and adding a padding to the left.Because of this the css I use to change the background colour of every other row is not available in the first column. Now I want to add a background colour to every other first-child of td so i tried
td {
&:first-child {
position:absolute;
left:0;
&:nth-child(even){
background-color: blue;
}
}
}
but this still selecting all the first td elements.
My question is why is this showing such a behaviour and is there a way to select the elements the way I want ?
CodePudding user response:
I'm a little confused but is this how you want it?
td:first-child {
position:absolute;
left:0;
}
tr:nth-child(even){
background-color: blue;
}
<table>
<tr>
<th>heading a</th>
<th>heading b</th>
<th>heading c</th>
</tr>
<tbody>
<tr>
<td>data 1</td>
<td>data 2</td>
<td>data 3</td>
<td>data 4</td>
</tr>
<tr>
<td>data 1</td>
<td>data 2</td>
<td>data 3</td>
<td>data 4</td>
</tr>
<tr>
<td>data 1</td>
<td>data 2</td>
<td>data 3</td>
<td>data 4</td>
</tr>
</tbody>
</table>
CodePudding user response:
I think this is how you want it?
tr:nth-child(odd) td:first-child {
position:absolute;
left:0;
background-color:blue;
}
<table>
<tr>
<th>heading a</th>
<th>heading b</th>
<th>heading c</th>
</tr>
<tbody>
<tr>
<td>data 1</td>
<td>data 2</td>
<td>data 3</td>
<td>data 4</td>
</tr>
<tr>
<td>data 1</td>
<td>data 2</td>
<td>data 3</td>
<td>data 4</td>
</tr>
<tr>
<td>data 1</td>
<td>data 2</td>
<td>data 3</td>
<td>data 4</td>
</tr>
</tbody>
</table>
td:first-child {
position:absolute;
left:0;
}
tr td:not(:first-child){
background-color: blue;
}
<table>
<tr>
<th>heading a</th>
<th>heading b</th>
<th>heading c</th>
</tr>
<tbody>
<tr>
<td>data 1</td>
<td>data 2</td>
<td>data 3</td>
<td>data 4</td>
</tr>
<tr>
<td>data 1</td>
<td>data 2</td>
<td>data 3</td>
<td>data 4</td>
</tr>
<tr>
<td>data 1</td>
<td>data 2</td>
<td>data 3</td>
<td>data 4</td>
</tr>
</tbody>
</table>