I want a different color only for first row of a html table
Solution 1
You can use :first-child for this. Write like this:
#table-4 tr:first-child{
background:red;
}
Check this http://jsfiddle.net/cbK8J/
Solution 2
@JonathandeM.'s comment is correct. Pop <thead>
and <tbody>
tags in there, and change the <td>
tags in the <thead>
row to <th>
tags (because HTML says what things are, and they're headings):
<table border='0' width='100%' id='table-4'>
<thead>
<tr><th scope="col">Date</th><th scope="col">Headline</th></tr>
</thead>
<tbody>
<tr><td>29 DEC</td><td>Dead</td></tr>
<tr><td>30 DEC</td><td>Hit</td></tr>
<tr><td>02 JAN</td><td>Leg</td></tr>
</tbody>
</table>
Then the CSS to make the heading row have a different background colour is:
#table-4 thead tr {
background-color: green;
}
Solution 3
you can do this:
HTML:
<td class="whatever">Date</td><td class="whatever">Headline</td>
css:
.whatever { color: #a9a9a9 }
<tr>
will do the row, <td>
will do the cells.
Related videos on Youtube
![Shahriar Kabir](https://i.stack.imgur.com/T0mpe.jpg?s=256&g=1)
Shahriar Kabir
I am studying Computer Science and Engineering at Khulna University of Engineering & Technology and I am a part time web developer.
Updated on October 15, 2022Comments
-
Shahriar Kabir over 1 year
I used a table. I applied CSS ID
table-4
.Following the html code:
<table border='0' width='100%' id='table-4'> <tr><td>Date</td><td>Headline</td></tr> <tr><td>29 DEC</td><td>Dead</td></tr> <tr><td>30 DEC</td><td>Hit</td></tr> <tr><td>02 JAN</td><td>Leg</td></tr> </table>
Here is the style.css:
#table-4 { background-color: #F2F2F2;}
So the whole table's background color is
#F2F2F2
, but I want a different color for the first row whereDate
andHeadline
goes, so how could I modify my CSS for this thing?-
Jonathan de M. over 11 yearsuse thead for your head, if cannot use table
tr:first-child td
selector -
Jonathan de M. over 11 years
-
Joe Dargie over 11 years@thirdender: "your first TR wrapped in a THEAD tag means "This column is the 'Date' column", "This column is the 'Headline", etc." - that's not quite right. the
<thead>
tag says "this section of the table is the heading section." It doesn't say that every cell in it is a column header. (See w3.org/TR/2011/WD-html5-author-20110809/…) You need<th>
cells with ascope
attribute for that.
-
-
Joe Dargie over 11 yearsOr you could use the
:first-child
selector. -
Marcin Buciora over 11 yearsok, you can '#table-4 tr:first-child { background-color: blue;}'
-
Shahriar Kabir over 11 yearsit's working, thanks. could you tell me how I can change text color of 1st row too?
-
Shahriar Kabir over 11 yearsit's working, thanks. could you tell me how I can change text color of 1st row too?
-
Marcin Buciora over 11 yearsjust add
color: white;
ie:#table-4 tr:first-child { background-color: blue; color: white}
-
sandeep over 11 yearssimple add your style properties inside the brackets. Check this jsfiddle.net/cbK8J/1