0

I'm trying to understand the nth-child selector.

With the following code I thought I would get first a "table" of 3 divs of equal width (95px), the first having padding right of 5px, the second having both padding left an right 2.5px, and the last having padding left of 5px

The second "table" would have two divs, the first having 195px width and padding right of 5px, and the last 9px width an 5px padding left.

Unfortunately the last div of the second "table" seems to have both padding left and right of 2.5px.

The rule responsible for this being:

div.table-td.w33:nth-child(2)

But there is only one div with both classes table-td and w33 in that group, so there should be no second child (nth-child(2))

div.table {
  width: 300px;
 background-color: black;
}

div.table-td {
 display: inline-block;
 vertical-align: top;
 padding-right: 5px;
 padding-left: 5px;
 background-color: grey;
}

div.table-td:first-child {
 padding-left: 0;
}

div.table-td:last-child {
    padding-right: 0 !important;
}

div.table-td.w33 {
 width: 33%;
 width: calc((100% / 3) - 5px);
}

div.table-td.w33:nth-child(2) {
 padding-right: 2.5px;
 padding-left: 2.5px;
}

div.table-td.w66 {
 width: 66%;
 width: calc(((100% / 3) * 2 ) - 5px);
}
<div class="table">
<div class="table-td w33">Should take 95px width with padding right of 5px</div>
<div class="table-td w33">Should take 95px width with padding right and left of 2.5px</div>
<div class="table-td w33">Should take 95px width with padding left of 5 px</div>
</div>

<div class="table">
<div class="table-td w66">Should take 195px width with padding right of 5px</div>
<div class="table-td w33">Should take 95px width with padding left of 5 px</div>
</div>

Could someone enlighten me. Where is the error in my thinking, or is this faulty browser rendering?

Pit
  • 1,448
  • 1
  • 18
  • 26
  • 1
    Essentially, there is no `nth-of-class` selector in CSS. Js/JQ **does** have this though. – Paulie_D Jun 16 '17 at 16:07
  • 1
    I know it has been answered, but If you want check this https://jsfiddle.net/vrzjjxgv/ check the comments on the relevant part of css where table has :nth-child(1) (2) – Julian Espinosa Jun 16 '17 at 16:17
  • 1
    @JulianEspinosa thanks, that helped me to understand what it did wrong. (better than the duplicate question) – Pit Jun 19 '17 at 06:09

0 Answers0