How to Select all Child Elements Recursively using CSS?
Last Updated :
13 Jan, 2025
Here are three methods to achieve to Select all Child Elements Recursively using CSS:
1. Using the Universal Selector (*)
The universal selector applies styles to all child elements within a parent recursively.
HTML
<html>
<head>
<style>
.parent * {
color: blue;
font-weight: bold;
}
</style>
</head>
<body>
<div class="parent">
<p>First child</p>
<div>
<p>Nested child</p>
</div>
</div>
</body>
</html>
In this Example:
- The * selector targets all descendant elements of .parent and applies the styles.
- It selects children at all levels, ensuring consistent styling.
2. Using Descendant Combinator ( )
The descendant combinator targets all nested child elements of a parent element.
html
<html>
<head>
<style>
.parent p {
color: green;
font-size: 18px;
}
</style>
</head>
<body>
<div class="parent">
<p>Direct child</p>
<div>
<p>Nested child</p>
</div>
</div>
</body>
</html>
In this Example:
- The descendant combinator (.parent p) applies styles to all <p> elements within .parent, regardless of nesting.
3. Using Direct Child Selector (>)
This method applies styles only to the direct children of a parent element.
html
<html>
<head>
<style>
.parent > p {
color: red;
text-decoration: underline;
}
</style>
</head>
<body>
<div class="parent">
<p>Direct child</p>
<div>
<p>Nested child</p>
</div>
</div>
</body>
</html>
In this Example:
- The > selector targets only the direct <p> children of .parent, leaving deeper descendants unaffected.