0
0
CssHow-ToBeginner · 3 min read

How to Select All Children in CSS: Simple Guide

To select all direct children of an element in CSS, use the parent > * selector. The * means all child elements directly inside the parent, allowing you to style them together.
📐

Syntax

The selector parent > * targets all direct child elements of the parent element. Here:

  • parent is the parent element's selector (like a class, id, or tag).
  • > means direct children only, not deeper descendants.
  • * means all child elements regardless of their tag name.
css
parent > * {
  /* styles here */
}
💻

Example

This example shows how to select and style all direct children of a div with class container. All child elements get a light blue background and padding.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Select All Children Example</title>
<style>
.container > * {
  background-color: #cce5ff;
  padding: 10px;
  margin: 5px 0;
}
</style>
</head>
<body>
  <div class="container">
    <p>Paragraph child</p>
    <button>Button child</button>
    <span>Span child</span>
    <div>
      <p>Nested paragraph (not styled)</p>
    </div>
  </div>
</body>
</html>
Output
A page with a container box where the paragraph, button, and span inside have a light blue background and padding. The nested paragraph inside the inner div is not styled.
⚠️

Common Pitfalls

One common mistake is using parent * instead of parent > *. The parent * selector styles all descendants, including nested children, which might not be what you want.

Also, forgetting the > combinator means you lose control over direct vs. indirect children.

css
/* Wrong: styles all descendants */
.container * {
  color: red;
}

/* Right: styles only direct children */
.container > * {
  color: red;
}
📊

Quick Reference

  • parent > *: Selects all direct children of parent.
  • parent *: Selects all descendants (children, grandchildren, etc.) of parent.
  • Use > to limit selection to direct children only.

Key Takeaways

Use parent > * to select all direct children in CSS.
The * selector means all element types.
The > combinator limits selection to direct children only.
Using parent * selects all descendants, not just direct children.
Always check your selector to avoid styling unintended nested elements.