2

I have a table where certain rows are highlighted. I want the first row of the highlighted rows to have a border applied to the top of it.

I'm trying the following, but it's not working.

.highlighted{
 background-color: lightyellow;
}
table:first-child tr.highlighted td{
    border-top: solid 1px gray;
}

Here is a fiddle.

http://jsfiddle.net/k2ky6/

The problem I'm having is that the border is added to every highlighted row, not just the first.

Is this possible with pure css?

Smeegs
  • 9,151
  • 5
  • 42
  • 78

3 Answers3

5

You can do it like this, with the selector .highlighted ~ .highlighted, and applying a display:block to your <tr>. Here is the updated jsFiddle

.highlighted {
    display:block;
    border-top:1px solid lightgrey;
    background-color:lightyellow;

}
.highlighted ~ .highlighted {
    border:0;
} 

What that does is the .highlighted applies to the first one, and the .highlighted ~ .highlighted applies to everything but the first one

scrblnrd3
  • 7,228
  • 9
  • 33
  • 64
1

The :first-child pseudo-selector is about being the first child of a parent element. If your <TR>s are all children of one common <TABLE> then tr:first-child applies only to the first row in the table.

What you actually wrote - table:first-child - applies to <TABLE> elements which are first children of their particular parent (first <TABLE> in a <DIV> for example).

You might get something working by putting each group of highlighted cells in a <TBODY> if that is possible for you - because then the <TR> would indeed be the first child of that <TBODY>.

As far as I know what you actually asked for - first <TR> with a particular class - is not possible at all in pure CSS, not even with the new CSS3 selectors.

drquicksilver
  • 1,627
  • 9
  • 12
1

Is there a benefit/difference to this .highlighted ~ .highlighted ?

...as opposed to creating a style for just the first highlighted one such as

.highlighted{
    background-color: lightyellow;
}
.highlighted-2 td{
    border-top: solid 1px gray;
    background-color: lightyellow;
}
Phlume
  • 3,075
  • 2
  • 19
  • 38
  • The benefit is that you don't have to change the source :-) If you assume the OP is unable to change the classes/structure of the original HTML then this is the pure CSS solution. If he is able to change things then of course there are lots of ways to do it differently with an additional or different class on the first element. – drquicksilver Dec 18 '13 at 15:29