brld
brld

Reputation: 188

Style only certain th in a table?

I'd like to be able to style only certain table headers in a HTML table. There are 8 table headers in total, and I want to select 4 of them.

I am not allowed to change any HTML, or add any JavaScript. Only CSS. The JSFiddle for the question is here: https://jsfiddle.net/gk0bwtvs/38/

table tr td {
  padding: 5px;
}
table {
  border: pink 5px;
  border-style: double;
}
table tr:nth-child(even) {
  background-color: #aaa;
}
<table>
  <tr>
    <td>&nbsp;</td>
    <th>January</th>
    <th>March</th>
    <th>June</th>
    <th>September</th>
  </tr>
  <tr>
    <th>Temperature</th>
    <td>Cold</td>
    <td>Maple syrup season!</td>
    <td>Warmer</td>
    <td>Cooling down</td>
  </tr>
  <tr>
    <th>Precipitation</th>
    <td>Snow</td>
    <td>Mud</td>
    <td>Rain</td>
    <td>Rain, but not for long</td>
  </tr>
  <tr>
    <th>Amount of Daylight</th>
    <td>Very little</td>
    <td>Even daylight and night</td>
    <td>Lots of daylight</td>
    <td>Even daylight and night</td>
  </tr>
  <tr>
    <th>Recommended Outerwear</th>
    <td>Heavy jacket</td>
    <td>It depends!</td>
    <td>Usually no jacket</td>
    <td>Light jacket sometimes</td>
  </tr>
</table>

I'm thinking something along the lines of:

table tr th+td:not(th+th) {
  color: green;
}

or maybe:

table tr th+td {
  color: green;
}

However neither of those seem to work.

I want to style “Temperature”, “Precipitation”, “Amount of Daylight” and “Recommended Outerwear” and not month headings. Also, I cannot use an nth-child or nth-of-type selector for this.

EDIT: Answer selected, thank you!

Upvotes: 0

Views: 67

Answers (2)

Seno
Seno

Reputation: 419

Based on jsfiddle you supplied, this is the selector that works:

table tr + tr > th {
  background-color: red;
  color: #FFF;
}

Explanation: It will not select the first tr and select the tr that next to a tr, and it will select th the direct child of the tr.

No nth-child or nth-of-type is used. Hope this helps.

Upvotes: 2

Prateek
Prateek

Reputation: 1556

You can try this: They are called as suedo selectors.

table tr th:first-child{
      background-color: green;
    }

Upvotes: 1

Related Questions