MeV MeV - 6 months ago 14
CSS Question

CSS child's element selector - HTML Email (CSS ONLY)

I am trying to find a way to change the css for a class, only if it's inside a table with 4 td's.
The code will probably explain better what is my problem.

HTML

<table class="myclass">
<tr>
<td>1 <span class="myclass2">xxx</span></td>
<td>2 <span class="myclass2">xxx</span></td>
<td>3 <span class="myclass2">xxx</span></td>
</tr>
</table>

<table class="myclass">
<tr>
<td>1 <span class="myclass2">xxx</span></td>
<td>2 <span class="myclass2">xxx</span></td>
<td>3 <span class="myclass2">xxx</span></td>
<td>4 <span class="myclass2">xxx</span></td>
</tr>
</table>


CSS

.myclass td:first-child:nth-last-child(3),td:first-child:nth-last-child(3) ~ td {
background-color:white !important;
}
.myclass td:first-child:nth-last-child(4),td:first-child:nth-last-child(4) ~ td {
background-color:red !important;
}
.myclass2 {
color:blue;
}


a JSFiddle is ready: JSFIDDLE HERE

What I am trying to do is changing the style of "myclass2" only for the elements included in the table with 4 TDs, not with the table with 3 TDs.
Is that possible at all?

Answer

It's possible, yes, but you would need to use multiple selectors, checking the that first cell was also the 4th last cell, the 2nd also the 3rd last, and so on:

.myclass2{
    background:#000;
    color:#fff;
}
td:first-child:nth-last-child(4) .myclass2,
td:nth-child(2):nth-last-child(3) .myclass2,
td:nth-child(3):nth-last-child(2) .myclass2,
td:nth-child(4):last-child .myclass2{
    background:#f00;
}
<table class="myclass">
    <tr>
        <td>1 <span class="myclass2">xxx</span></td>
        <td>2 <span class="myclass2">xxx</span></td>
        <td>3 <span class="myclass2">xxx</span></td>
    </tr>
</table>
<table class="myclass">
    <tr>
        <td>1 <span class="myclass2">xxx</span></td>
        <td>2 <span class="myclass2">xxx</span></td>
        <td>3 <span class="myclass2">xxx</span></td>
        <td>4 <span class="myclass2">xxx</span></td>
    </tr>
</table>

Or, alternatively, just select the first child that is also the fourth last child and any cells that follow it:

.myclass2{
    background:#000;
    color:#fff;
}
td:first-child:nth-last-child(4) .myclass2,
td:first-child:nth-last-child(4)~td .myclass2{
    background:#f00;
}
<table class="myclass">
    <tr>
        <td>1 <span class="myclass2">xxx</span></td>
        <td>2 <span class="myclass2">xxx</span></td>
        <td>3 <span class="myclass2">xxx</span></td>
    </tr>
</table>
<table class="myclass">
    <tr>
        <td>1 <span class="myclass2">xxx</span></td>
        <td>2 <span class="myclass2">xxx</span></td>
        <td>3 <span class="myclass2">xxx</span></td>
        <td>4 <span class="myclass2">xxx</span></td>
    </tr>
</table>