Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
CSS Descendant Selector
The descendant selector in CSS is used to match all elements that are descendants of a specified element. It allows you to apply styles to nested elements without affecting elements outside the parent container.
Syntax
ancestor descendant {
property: value;
}
The descendant selector uses a space between the ancestor and descendant elements. It selects all descendant elements, regardless of how deeply nested they are within the ancestor.
Example
You can try to run the following code to implement CSS Descendant Selector −
<!DOCTYPE html>
<html>
<head>
<style>
div p {
background-color: orange;
padding: 10px;
margin: 5px 0;
}
</style>
</head>
<body>
<div>
<p>Para 1 in the div</p>
<p>Para 2 in the div</p>
</div>
<p>Para 3 outside the div.</p>
</body>
</html>
Para 1 and Para 2 appear with orange background and padding, while Para 3 remains unstyled with default appearance.
Nested Descendant Example
The descendant selector also works with deeply nested elements −
<!DOCTYPE html>
<html>
<head>
<style>
.container span {
color: blue;
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<p>This paragraph contains <span>blue text</span> inside.</p>
<div>
<span>This span is also blue</span>
</div>
</div>
<span>This span is outside and not styled</span>
</body>
</html>
The spans inside the container div appear in blue bold text, while the span outside remains with default styling.
Conclusion
The descendant selector is a powerful tool for applying styles to nested elements. It uses a space between selectors and affects all matching descendants, regardless of nesting depth.
