Can someone explain how multiple inline nth-child() works?

Issue

For example I might have this:

html>body>#wrapper>div>div>div:nth-child(1)>div:nth-child(1)>nav {

What exactly does that do? Can someone break down each div, ">", and nth-child()? Thank you. Trying to figure out how this works.

Solution

> is the child selector. Note the difference between a descendant and a child. The css selector .a .b matches any element with a class of b which is a descendant of an element with a class of a, whereas the css selector .a>.b matches any element with a class of b which is a child of an element with a class of a. All children are also descendants, but only first-generation descendants are children.

So:

  • #wrapper matches an element with the id of wrapper
  • #wrapper>div matches div elements which are children (first-generation descendants) of #wrapper
  • #wrapper>div>div matches div elements which are children of div elements which are children of #wrapper
  • #wrapper>div>div>div:nth-child(1) matches div elements which are the first child of div elements which are children of div elements which are children of #wrapper
  • #wrapper>div>div>div:nth-child(1)>div:nth-child(1) matches div elements which are the first child of div elements which are the first child of div elements which are children of div elements which are children of #wrapper
  • #wrapper>div>div>div:nth-child(1)>div:nth-child(1)>nav matches nav elements which are children of div elements which are the first child of div elements which are the first child of div elements which are children of div elements which are children of #wrapper

This is pretty crazy CSS. Much better to give the nav element an id or a class and then use much simpler selectors in CSS:

<nav id="nav1" class="top-nav">
<style>
  #nav1 { ... rules here ... }
  .top-nav { ... rules here ...}
</style>

Answered By – Brett Donald

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.