• Post category:CSS

Descendant Selector CSS Example | Full Explained

Descendant selector CSS example

This article is about CSS descendant selector with example.

What is Descendent?

<div>
<header>
<h2> Heading Text </h2>
</header>
<content>
<a href="#">Anchor Text</a>
</content>
<footer>
<p>Paragraph Text</p>
</footer>
<div>

The Descendents of a node is any node falling under the selected node tree. (i.e. Direct children, children’s children, and so on, or any node that can be reachable from the selected node to the leaf nodes are considered as descendants of the node). In the above code, the <div> is Descendents are directed children which are <header>, <content> and <footer> elements. The children’s children is <h2>, <a> and <p> elements, all this are descendent.

It selects any HTML element targeted by the selector written after the space character, which is a descendent of the HTML element targeted by the selector written before the space character.

Syntax of descendent selector

selector1 selector2
{
border: 2px solid red;
}
</style>

It selects any HTML element targeted by selector2, which is a “descendent” of any HTML element targeted by selector1.

Example for a descendent selector

CSS:

div p
{
border: 2px solid red;
}

HTML:

<div>
<h2>Heading Text</h2>
<p>Paragraph Text</p>
<a href="#">Anchor Text</a>
<div>

Output:

descendant selector css example
In the above code, we have <h2>, <p> and <a> elements inside the <div>. In CSS, select “div p” and in the flower brackets, we have written 2px red border. It selects any<p> element, which is descendent of any <div> element. Here we telling to the system, to locate any <div> if it has a descendent with the <p> and apply the border styles.

Leave a Reply