java12399900
java12399900

Reputation: 1671

CSS: Changing color on text in specifc column - but not on that column header?

I have the following HTML table:

<div class="table">
            <table id="carTable">
                <tbody>
                <tr>
                    <th>Car Number</th>
                    <th>owner</th>
                </tr>
                <!-- {{#each car}} -->
                <tr>
                    <td>{{carNumber}}</td>
                    <td>{{owner}}</td>
                </tr>
                <!--{{/each}} -->
                </tbody>
            </table>
        </div>

And associated CSS that changes colour of text in first column:

#carTable tr>:nth-child(1){
        font-weight: bold;
        color: #2d89ac;
    }

The problem is that this is also changing the color on the table header of that column.

How can I stop it doing so?

Upvotes: 1

Views: 491

Answers (2)

vogomatix
vogomatix

Reputation: 5041

You should put your column titles in a thead (table header) section.

Although there are exceptions, putting your column titles in the tbodyis not generally good practice. Having the column titles in a separate header section permits scrolling of the body of the table whilst keeping the column titles in view.

<table id="carTable">
  <thead>
    <tr>
      <th>Car Number</th>
      <th>owner</th>
    </tr>
  </thead>
  <tbody>
    <!-- {{#each car}} -->
    <tr>
      <td>{{carNumber}}</td>
      <td>{{owner}}</td>
    </tr>
    <!--{{/each}} -->
  </tbody>
</table>

Then you could add a tbody selector in your CSS rule.

#carTable tbody tr>:nth-child(1){
    font-weight: bold;
    color: #2d89ac;
}

Upvotes: 4

johannchopin
johannchopin

Reputation: 14843

You can use the :not() rule in css:

#carTable tr>:nth-child(1):not(th) {
  font-weight: bold;
  color: #2d89ac;
}
<div class="table">
  <table id="carTable">
    <tbody>
      <tr>
        <th>Car Number</th>
        <th>owner</th>
      </tr>
      <!-- {{#each car}} -->
      <tr>
        <td>{{carNumber}}</td>
        <td>{{owner}}</td>
      </tr>
      <!--{{/each}} -->
    </tbody>
  </table>
</div>

Upvotes: 2

Related Questions