I wrote something like this in CSS:
tr.red > td:not(:last-of-type):not(:first-of-type)
{
color: #E53B2C;
border-bottom: 4px solid #E53B2C;
}
I'm trying to apply this to table cells, which are not first and not last in the row with .red
class.
It seems to work as expected, but is this really the right way to do it?
It is syntactically correct, as you can quickly check using the W3C CSS Validator. The validator is known to have errors, so in principle, you should check the rule against CSS specifications, especially Selectors Level 3. The result is still that yes, it is correct.
It also has the desired meaning, since this is how selectors combine. You can use :not(...)
selectors to express a condition of type “not ... and not ...”.
This applies provided that all children of tr
elements are td
. If there are header cells, i.e. th
elements as well, then the selector applies to those data cells (td
elements) that are not the first data cell or the last data cell in a row with .red
class.
May be this would help
tr.red td:not(:first-child):not(:last-child)
{
//your styles
}
Sample
As some told, td:first-of-type gives you first TD, where td:first-child selects the first child element of that tR if it's TD. This means, your code won't give you all the cells that aren't first or last if you have any TH.
tr.red > *:not(:last-child):not(:first-child)
{ /* ... your css code ... */ }
I think it should work well this way. Even if you wanted to have separate code for TH and TD, you could do it like th:not(:first-child) and td:not(:first-child). Your code would be better when you want to find first element with some tag name, like p:first-of-type and give it some different style.