Difference between Immediate Child and First-Child?

Asked

Viewed 71 times

5

Could someone help me with the difference between these two concepts?

From what I understand both mean the same thing...but by performing the test below, the text was left with the format of the pseudo-selector

div > p {
    font-family: Garamond;
}

p:first-child {
    font-family: cursive;
}

3 answers

4


Look at the example:

div>p {
  font-family: Garamond;
  color: brown;
  text-decoration: underline;
}

p:first-child {
  font-family: cursive;
  color: blue;
}
<div>
  <p>Primeiro</p>
  <p>Segundo</p>
  <p>Terceiro</p>
  <section>
    <p>Neto um</p>
    <p>Neto dois</p>
    <nav>
      <span>Bisneto um</span>
      <p>Bisneto dois</p>
    </nav>
  </section>

</div>

The selector div > p causes all immediate children of div receive css rules. In the example would be p with text: First, Second, Third.

These rules do not spread to p inside section for these are no longer immediate children of div, but "grandchildren".


The selector p:first-child says that all the p page (regardless of which parents have) who are the first child of a given element, will have these rules.

Notice that Primeiro and Neto um receive these rules, but not Bisneto dois this despite being the first p of this level, but it is the second child, not the first.

  • 1

    Thank you for the excellent answer, Sergio!

  • @Great kidmalo I could help!

1

Simple, Immediate Child selects all corresponding children

first-child selects the first corresponding child

Following your example if you only have one element p there will be no difference because it will be the first son and immediate son, but if you have more than one there the first-child will select only the first and the Immediate Child all immediate.

  • Thank you for that excellent reply, Lennon!

1

Immediate Child

Selects an element that is child DIRECT other element.

For example

div > span

Select only the first and third span that are direct children.

    <div>
       <span>Essa é filha direta</span>
       <p>
          <span>Essa NÃO é filha direta.</span>
       </p>
       <span>Essa é filha direta</span>
    </div>

First Child

Selects all elements of the type that are FIRST children of other elements.

For example

p:first-child

Will select only the paragraphs that are first children of other elements

<div>
   <p>Este sera selecionado</p>
   <p>Este NÃO sera selecionado</p>
</div>

<div>
   <h1>Este não é paragrafo</h1>
   <p>Este NÃO será selecionado</p>
</div>
  • Thank you for the excellent answer, Fabri!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.