mizech mizech - 20 days ago 6
CSS Question

CSS "grandchild" selector * : Is there a difference between "parent child" and "parent * child"

I've known about the existence of a so-called "grandchild" selector in CSS until I've seen this article / video: https://www.sitepoint.com/premium/screencasts/atoz-css-the-general-sibling-selector

I've played around with it. It seems to me as being just the universal selector (which selects all elements).

I've made this demo:



.wrap {
width: 400px;
height: 300px;
margin: 50px auto;
}

.wrap * p {
width: 400px;
height: 100px;
background-color: green;
margin: 10px;
color: red;
}

<div class="wrap">
<div class="item1">
<p>First</p>
<div class="item2">
<p>Second</p>
<div class="item3">
<p>Third</p>
</div>
</div>
</div>
</div>





If one remove the * from the ".wrap * p" nothing changes.

It's basically the same as ".wrap p" (parent blank child).

So therefore my question:

Does the "grandchild" selector make any sense?

Is there a difference to using the "parent blank child" notation?

Answer

Yes, there is a difference.

* is a universal selector which can match any child.

.wrap * p means select all p elements which exists on 2nd or more level in parent child relationship. It will work only when there will be some element present between .wrap and p. This selector will not work if p is direct child of .wrap.

In your code if you will make p element direct child of .wrap i.e.

<div class="wrap">
  <p>First</p> // <== (.wrap * p) cannot select this element while (.wrap p) can.
  <div class="item1">
    <p>First</p>
    <div class="item2">
      <p>Second</p>
      <div class="item3">
        <p>Third</p>
      </div>
    </div>
  </div>
</div>