Reputation: 3518
I want to style all table cells with background-color:blue, when they are inside a table with class="p1". The following works, but it is long:
table.p1 > tbody > tr > td,
table.p1 > thead > tr > td,
table.p1 > tbody > tr > th,
table.p1 > thead > tr > th{
background-color:blue;
}
Is there a shorter/more elegant way to define this CSS rule?
Edit: only the table cells immediately contained by table "p1" may be styled, and no further children (such as nested tables inside those cells)
Upvotes: 4
Views: 22070
Reputation: 3518
Figured out a much shorter version. I remembered that you can use asterisk * for any element. Knowing that the table tag may only immediately contain tbody/thead, and tr may only immediately contain td/th, I revised the CSS class to the following:
.p1 > * > tr > * {
background-color:blue;
}
Upvotes: 12
Reputation: 301
Three things I'd fix:
table.p1
is overly specific. This isn't a best practice.The tbody
, thead
, and tr
levels are unecessary, unless you plan on nesting td
's.
.table-p1 td, .table-p1 th {
background-color:blue;
}
Edit: Given the updated nesting requirement to the question, I would propose creating two table classes:
.table-normal td, .table-normal th { background-color: grey; }
.table-p1 td, .table-p1 th { background-color: blue; }
Then you could just add the .table-normal
class for nested tables inside .table-p1
and avoid all these fancy, brittle selectors.
Upvotes: 3
Reputation: 4413
If that is your requirement, that you need to use the direct children selector, then i don't believe there is any way you can do it. You can remove the white spaces in-between but that is about it. Only other way is to add a specific class name to the cells you want to target...
Upvotes: 0