Nick Grealy Nick Grealy - 2 months ago 6
CSS Question

CSS > Highlight first row if more than 2 columns wide

I want to apply styling to a table made up solely of

<td>
's, to highlight a header row/column, based on the number of columns in a table.

The trick is, I don't want it to clash with tables that do have a
<th>
cells setup correctly.

Browser: Chrome v53 (64bit on MacOS)

What I've tried: http://jsbin.com/tacevu/edit?html,css,output

I'm almost there, I just can't highlight the first row if a table has more than 2 columns (i.e. scenario "Table 4"). Perhaps Chrome doesn't support the
!
parent selector?



/* highlight first ROW if > 2 columns*/
tr:first-child! td:nth-last-child(4) { background-color:blue; }


<table>
<caption>Table 4</caption>
<tr>
<td>aaa</td><td>bbb</td><td>aaa</td><td>bbb</td>
</tr><tr>
<td>aaa</td><td>bbb</td><td>aaa</td><td>bbb</td>
</tr><tr>
<td>aaa</td><td>bbb</td><td>aaa</td><td>bbb</td>
</tr>
</table>

Answer

Try This n+3 child for more than 2 child

 tr:first-child td:nth-last-child(n+3) ~ td,
 tr:first-child td:nth-last-child(n+3):first-child{
    background-color: blue;

}

table,
tr,
td,
th {
  border: 1px solid grey;
}
/* highlight TH */

th {
  background-color: red;
}
/* highlight first COLUMN if 2 columns */

td:nth-last-child(2):first-child {
  background-color: lime;
}
/* highlight first ROW if > 2 columns*/

tr:first-child td:nth-last-child(n+3) ~ td,
tr:first-child td:nth-last-child(n+3):first-child {
  background-color: blue;
}
<table>
  <caption>Table 1</caption>
  <tr>
    <th>aaa</th>
    <td>bbb</td>
  </tr>
  <tr>
    <th>aaa</th>
    <td>bbb</td>
  </tr>
  <tr>
    <th>aaa</th>
    <td>bbb</td>
  </tr>
</table>

<br/>

<table>
  <caption>Table 2</caption>
  <tr>
    <td>aaa</td>
    <td>bbb</td>
  </tr>
  <tr>
    <td>aaa</td>
    <td>bbb</td>
  </tr>
  <tr>
    <td>aaa</td>
    <td>bbb</td>
  </tr>
</table>

<br/>

<table>
  <caption>Table 3</caption>
  <tr>
    <th>aaa</th>
    <th>bbb</th>
    <th>aaa</th>
    <th>bbb</th>
  </tr>
  <tr>
    <td>aaa</td>
    <td>bbb</td>
    <td>aaa</td>
    <td>bbb</td>
  </tr>
  <tr>
    <td>aaa</td>
    <td>bbb</td>
    <td>aaa</td>
    <td>bbb</td>
  </tr>
</table>

<br/>

<table>
  <caption>Table 4</caption>
  <tr>
    <td>aaa</td>
    <td>bbb</td>
    <td>aaa</td>
    <td>bbb</td>
  </tr>
  <tr>
    <td>aaa</td>
    <td>bbb</td>
    <td>aaa</td>
    <td>bbb</td>
  </tr>
  <tr>
    <td>aaa</td>
    <td>bbb</td>
    <td>aaa</td>
    <td>bbb</td>
  </tr>
</table>

PC: http://lea.verou.me