Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
157
rated 0 times [  159] [ 2]  / answers: 1 / hits: 17282  / 12 Years ago, tue, november 6, 2012, 12:00:00

How can i use css or jquery to add border-top only on the first row in a table?



I'm using the code below to get border on every td, but i need a border for the first row on top as well.



I cannot use CSS3 in this project btw.



What i have:



content






content






content






What i want:






content






content






content






.MyCarTable td {
border-bottom: 1px solid grey;
}

More From » jquery

 Answers
22

Everything can be done with CSS only which is in this case preferred way becuase of performance reasons. Don't use javascript unless you actually have to because it can't be done in any other way.



Solution 1: use first-child pseudo class



Add additional style definition.



.MyCarTable td {
border-bottom: 1px solid #ccc;
}
.MyCarTable tr:first-child td {
border-top: 1px solid grey;
}


And don't worry. This particular pseudo class has been long supported in browsers. Even IE supports it since version 7. Here's a JSFiddle that shows this working.



Solution 2: table header using th elements



If your table has header row, then use th elements instead of td in it and set different styling for header cells. But use this only when semantic content of your first row cells is actually cell header description for rows underneath. Otherwise I wouldn't suggest it.



Consecutive tables problem



If you have consecutive tables within the same container then next tables get top borders from previous table's last row. And you don't want them to apply top border on first row because that duplicates borders.



The solution (as seen in this JSFiddle) is similar and also applies to first table only:



.MyCarTable td {
border-bottom: 1px solid #ccc;
}
.MyCarTable:first-child tr:first-child td {
border-top: 1px solid #f99;
}​


As you can see top row's borders are only set for first table and first row within it. All consecutive tables won't set it. This example is of course only compatible with first solution above. If you'd taken the path with th elements then a combination of both should be used (th and pseudo classes).



But as you've said you've consolidated your repeater code.


[#82161] Monday, November 5, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
eliza

Total Points: 732
Total Questions: 96
Total Answers: 86

Location: Guam
Member since Fri, Jun 18, 2021
3 Years ago
;