Chris Hodges
Chris Hodges

Reputation: 73

CSS for specific table rows

I have a simple table with several rows. The top rows contains headings, while the rows under it have the id attribute of data. I have been trying to set CSS for the table rows that only have the id attribute data, but have so far only been able to set it for the entire table.

<table width = "80%" align="center" id="example">
<tr>
<td><h3>ID</h3></td>
<td><h3>First Name</h3></td>
<td><h3>Last Name</h3></td>
</tr>
<tr id="data">
<td>1</td>
<td>Joe</td>
<td>Schmoe## Heading ##</h3><td>
</tr>
</table>

and the CSS. I tried changing #example tr to tr #data with no luck. I know that I am overlooking something simple, but I am unsure what.

table#example {
    border-collapse: collapse;   
}
tr #data{
    background-color: #eee;
    border-top: 1px solid #fff;
}
tr #data:hover {
    background-color: #ccc;
}
tr #data {
    background-color: #fff;
}
tr #data th, tr #data td {
    padding: 3px 5px;
}
tr #data td:hover {
    cursor: pointer;
}

I'm not using classes because I'm not familiar enough with CSS and being able to use id only once is not a limitation for what I need.

Upvotes: 2

Views: 3449

Answers (1)

Jonah Bishop
Jonah Bishop

Reputation: 12581

You could use a class, but better yet, don't use classes at all (HTML markup is your friend)! Here's a clean solution to your problem:

HTML

<table>
    <tr>
        <th>ID</th>
        <th>First Name</th>
        <th>Last Name</th>
    </tr>
    <tr>
        <td>1</td>
        <td>Joe</td>
        <td>Schmoe</td>
    </tr>
</table>

CSS

th {
  font-weight: bold;
  /* More styles here */
}

td {
  background: #EEE;
  border-top: 1px solid #FFF;
}

tr:hover td {
  cursor: pointer;
  background: #CCC;
}

/* Styles upon styles */

Simply use the th element to specify the table header. To get each table data row to highlight as you mouse over it, simply use the tr:hover td rule to catch that case. See this fiddle for a working example.

Upvotes: 5

Related Questions