A distinction exists.
Offspring of a main element can fall into 2 categories:
- Direct Offspring.
- Indirect Offspring.
For instance, look at the provided code snippet below:
<div>
<em>This is direct offspring</span>
<p>
p is also a direct offspring.
<span>This is indirect offspring</span>
</p>
</div>
In the above example, <em>
and <p>
are direct offspring while <span>
is an indirect offspring of <div>
.
Offspring Selector:
In CSS, a space acts as an offspring selector. For example:
div p { ... }
The mentioned selector will target all <p>
elements within <div>
(both direct and indirect).
In the given code excerpt, all p
elements will inherit styles.
.wrap p {
background: green;
color: white;
}
<div class="wrap">
<p>Direct p of wrap</p>
<div class="item1">
<p>Indirect p of wrap</p>
<div class="item2">
<p>Indirect p of wrap</p>
</div>
</div>
</div>
Direct Offspring Selector:
>
serves as a direct offspring selector. For example:
div > p { ... }
The above selector will choose all <p>
elements that are direct offspring of <div>
. This selector only looks for elements one level down in the DOM tree.
In the following snippet, only direct p
offspring will receive styles.
.wrap > p {
background: green;
color: white;
}
<div class="wrap">
<p>Direct p of wrap</p>
<div class="item1">
<p>Indirect p of wrap</p>
<div class="item2">
<p>Indirect p of wrap</p>
</div>
</div>
</div>
Now, What does *
selector do?
*
is a universal selector that can match any element.
Indirect Offspring Selectors:
We can include the *
operator between two selectors to solely select indirect offspring. For example:
div * p { ... }
The above selector will pick all <p>
elements within <div>
that are indirect offspring (not direct). The *
selector placed between div
and p
will specifically choose <p>
when there is another element present between <div>
and <p>
(due to *
being a universal selector).
In the subsequent snippet, only indirect p
offspring will adopt styles.
.wrap * p {
background: green;
color: white;
}
<div class="wrap">
<p>Direct p of wrap</p>
<div class="item1">
<p>Indirect p of wrap</p>
<div class="item2">
<p>Indirect p of wrap</p>
</div>
</div>
</div>