0

Why are the "a tags" classified as descendants and not children? They look like they could be children rather than descendants. However, both lines of code below affect them the same way.

<p class="note">
  This page was written by
  <a href="mailto:ivy@example.com">ivy@example.com</a>
  <a href="http://www.example.com</a>
</p>

When I use the child selector:

p a {
  color: green;
}

a tags are green

When I use the descendant selector:

p > a {
  color: green;
}

a tags are green

What makes a descendant a descendant and a child a child?

Bertrand Le Roy
  • 17,731
  • 2
  • 27
  • 33
Shulkin
  • 47
  • 6
  • 1
    You've got your selector names mixed up. `>` is the child selector. In your case, the only descendants are children, so there is no difference. Wrap one of the anchors in a `span` or something and watch one of the selectors stop working. – Heretic Monkey Dec 05 '19 at 20:05
  • Children are a subset of descendants. Both selectors work because the `a` elements are both children and descendants. – John Skiles Skinner Dec 05 '19 at 20:06

2 Answers2

0

In this case, all the elements inside the p container are both children and descendants, so the child and descendant combinators will render the same output.

If your HTML looked like this:

<p class="note">
   This page was written by
   <a href="mailto:ivy@example.com"><span style="color: blue">ivy@example.com</span></a>
   <a href="http://www.example.com</a>
</p>

… then the span element would be a descendant of the p container, but not a child.

Think of a normal family. Parents have children. They are both children (>) and descendants () of the parents. The children then have children. These are descendants () of the original parents, but not their children (>).

Put another way, a child element is always a descendant, but a descendant is not always a child.


Spec reference:

2. Selectors

E F means an F element descendant of an E element

E > F means an F element child of an E element

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
0

If you use p a then style is applied to all a elements, that are inside any p element.

If you use p > a then style is applied to all a elements, which parent is p element.


For example, if you have
<p> <h1> <a> something </a> </h1> <p> (don't mind sense of that DOM structure)
then a element is not targetted by p > a, but is targetted by p a.


You can read more here.

Gaben
  • 345
  • 1
  • 12