0
0
CSSmarkup~5 mins

Child selector in CSS

Choose your learning style9 modes available
Introduction

The child selector helps you style only direct children of an element. It keeps your styles neat and specific.

You want to style only the immediate list items inside a menu, not nested submenus.
You want to add spacing only between direct paragraphs inside a section, ignoring paragraphs inside divs.
You want to color only the first-level headings inside an article, not headings inside nested elements.
You want to apply a border only to direct child images inside a container, not images inside nested elements.
Syntax
CSS
parent > child { 
  property: value;
}

The > symbol means 'direct child'.

It selects only elements that are immediate children, not deeper descendants.

Examples
This styles only list items that are direct children of an unordered list.
CSS
ul > li {
  color: blue;
}
This adds top margin only to paragraphs directly inside a div.
CSS
div > p {
  margin-top: 1rem;
}
This makes only the direct h2 headings inside a section bold.
CSS
section > h2 {
  font-weight: bold;
}
Sample Program

This example colors direct list items green and bold. Nested list items inside another list are gray and normal weight.

CSS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Child Selector Example</title>
  <style>
    ul > li {
      color: green;
      font-weight: bold;
    }
    ul li li {
      color: gray;
      font-weight: normal;
    }
  </style>
</head>
<body>
  <ul>
    <li>Direct child item 1</li>
    <li>Direct child item 2
      <ul>
        <li>Nested child item 1</li>
        <li>Nested child item 2</li>
      </ul>
    </li>
    <li>Direct child item 3</li>
  </ul>
</body>
</html>
OutputSuccess
Important Notes

Use the child selector to avoid styling nested elements unintentionally.

It helps keep your CSS organized and predictable.

Summary

The child selector > targets only direct children.

It is useful for precise styling in nested HTML structures.

It keeps styles from affecting deeper nested elements.