Descendant Selector in CSS
Let us have a list ul
and a list ol
:
<ul>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
</ul>
<ol>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
</ol>
Let's color the li
tags in these lists red:
li {
color: red;
}
Now suppose we want to color the tags li
of the list ul
red, and the tags li
of the list ol
green.
In this case, the descendants selector will help us. It allows you to select tags by their parent. To do this, you need to specify the parent selector, and after a space - the descendant selector. In our case, the ul li
selector will select all li
tags from the ul
list, and the ol li
selector will select all li
tags from the ol
list. Let's paint them in the desired colors:
ul li {
color: red;
}
ol li {
color: green;
}
A descendant selector does not have to consist of two tag selectors - there can be any number of them, separated by spaces. The following code, for example, selects all i
tags that are inside the li
tag, which in turn are inside the ul
tag:
ul li i {
color: red;
}
The following code is given:
<ul>
<li>text <i>italic</i></li>
<li>text <i>italic</i></li>
<li>text <i>italic</i></li>
<li>text <i>italic</i></li>
</ul>
<p>
paragraph text <i>italic</i>
</p>
<p>
paragraph text <i>italic</i>
</p>
Color the italics from the ul
tags red, and the italics from the p
tags green.
The following code is given:
<p>
paragraph text <b><i>bold italic</i></b>
</p>
<p>
paragraph text <i>italic</i>
</p>
Color the italics inside the b
tag red, which in turn is inside the p
tag.