CodeLives CodeLives -4 years ago 81
CSS Question

Can someone explain what this complex css does

.col-md-auto:first-child:nth-last-child(3),
.col-md-auto:first-child:nth-last-child(3) ~ .col-md-auto {
width: 33.3333%;
}


I came across this css on source code of a website and trying my hard to guess what it actually does.I am a newbie so finding it complex to deal with this complex css.I look at the w3 schools to figure out what those symbols means i could get the meaning of symbols but still could not figure out what the whole expression is doing.Any suggestions will be great help.

Answer Source

If there are exactly 3 elements with a class="col-md-auto" which are siblings, style them each with 1/3 width of the parent container.

Following on 4castle explanation:

:nth-child()

The :nth-child(an+b) CSS pseudo-class matches an element that has an+b-1 siblings before it in the document tree, for a given positive or zero value for n. More simply stated, the selector matches a number of child elements whose numeric position in the series of siblings matches the pattern an+b.

nth-last-child()

The :nth-last-child(an+b) CSS pseudo-class matches an element that has an+b-1 siblings after it in the document tree, for a given positive or zero value for n.

General sibling selector ~

The ~ combinator separates two selectors and matches the second element only if it is preceded by the first, and both share a common parent.


.col-md-auto:first-child:nth-last-child(3),
.col-md-auto:first-child:nth-last-child(3)~.col-md-auto {
  width: 33.3333%;
}

.col-md-auto:first-child:nth-last-child(3) selects the first element, while .col-md-auto:first-child:nth-last-child(3)~.col-md-auto selects the elements following the first child, but not the first-child itself, that's why the first selector is required.

.col-md-auto:first-child:nth-last-child(3),
.col-md-auto:first-child:nth-last-child(3)~.col-md-auto {
  width: 33.3333%;
}

.row {
  margin: 1em 0;
}

.row::after {
  display: table;
  content: " ";
  clear: both;
}

.col-md-auto {
  background-color: dodgerblue;
  height: 5em;
  float: left;
  width: 100%;
}

.col-md-auto:nth-child(even) {
  background-color: violet;
}
<div class="row">
  <div class="col-md-auto"></div>
  <div class="col-md-auto"></div>
  <div class="col-md-auto"></div>
</div>

<div class="row">
  <div class="col-md-auto"></div>
  <div class="col-md-auto"></div>
  <div class="col-md-auto"></div>
  <div class="col-md-auto"></div>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download