Select tr elements to style only for specific table

Viewed 1225

I want to style the odd and even rows of the <tr> selector of a <table>. There are multiple tables on the page and I only want to apply to a specific one.

Is it possible to use what I have below (or something similar) to only apply to a specific table without applying to every <tr> element on the page in every table?

tr:nth-child(even) td {
    background: #F1F1F1;
}

tr:nth-child(odd) td {
    background: #FEFEFE;
}


//here is my table
<table id="customDatesTable" class="tableStyle tableMaxWidth">
   <tr>
       <th width='15' align="left">
          Start Date
       </th>
       <th width="23" align="left">
          End Date
       </th>
       <th width="6" align="left">
          Intake#
       </th>
       <th width="10" align="left">
           Intake?
       </th>
   </tr>
   @foreach (var date in Model.CustomDates)
    {
        <tr>
            <td>@date.StartDate</td>
            <td>@date.EndDate</td>
            <td class="paddingCurrentDates">@date.IntakeNumber</td>
            <td class="paddingCurrentDates"><input type="checkbox" 
            checked="@(date.Intake)" id="intakeCheckBox" disabled /></td>
        </tr>
    }
</table>
1 Answers

You really should try to add an class to the table to use it for a specific table styling. then you can reuse this class for other tables in the future. The other approaches should only be used if this is not possible. An identifier can only be used once on the page. So when another table needs the same styling later you need to change it. And based on position is even worse because if there is a table added on the page in the future the styling will shift to another table and mess it up.

Based on table id would look like this

#yourtableid tr:nth-child(even) td {
     background: #F1F1F1;
}
#yourtableid tr:nth-child(odd) td {
     background: #FEFEFE;
}

Based on table class would look like this

table.yourtableclass tr:nth-child(even) {background: #F1F1F1}
table.yourtableclass tr:nth-child(odd) {background: #FEFEFE}

If it is the first table on the page it would be something like this.

table:first-of-type tr:nth-child(even) td {
     background: #F1F1F1;
}
table:first-of-type tr:nth-child(odd) td {
     background: #FEFEFE;
}
Related