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
What is greater-than sign (>) selector in CSS?
In CSS, the greater-than sign (>) is used as a child combinator selector. It selects only the direct children of a parent element, not elements that are nested deeper in the hierarchy.
Syntax
parent > child {
/* CSS styles */
}
In the above syntax, parent is the parent element, and child is the direct child element. The styles are applied only to the direct children, not to grandchildren or deeper nested elements.
Example 1: Basic Direct Child Selection
The following example demonstrates how the > selector works with an ordered list
<!DOCTYPE html>
<html>
<head>
<style>
ol > li {
color: blue;
font-weight: bold;
}
</style>
</head>
<body>
<h3>Direct Child Selector Example</h3>
<ol>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
<li>NodeJS</li>
</ol>
</body>
</html>
A numbered list with blue, bold text appears. All list items are styled because they are direct children of the ol element.
Example 2: Direct vs Descendant Selectors
This example shows the difference between the direct child selector (>) and the descendant selector (space)
<!DOCTYPE html>
<html>
<head>
<style>
div > p {
color: red;
font-weight: bold;
}
div p {
background-color: lightblue;
padding: 5px;
}
</style>
</head>
<body>
<h3>Direct Child vs Descendant Selector</h3>
<div>
<p>This is a direct child of div</p>
<h4>
<p>This is a grandchild of div</p>
</h4>
<span>
<p>This is also a grandchild of div</p>
</span>
</div>
</body>
</html>
The first paragraph appears in red bold text with light blue background. The nested paragraphs have only the light blue background but are not red or bold, demonstrating that the > selector targets only direct children.
Example 3: Multiple Level Selection
You can chain multiple > selectors to target elements at specific nesting levels
<!DOCTYPE html>
<html>
<head>
<style>
.container > ul > li {
color: white;
background-color: green;
padding: 8px;
margin: 2px;
list-style-type: none;
}
</style>
</head>
<body>
<h3>Multiple Level Direct Child Selection</h3>
<div class="container">
<ul>
<li>Item One</li>
<li>Item Two</li>
<li>Item Three</li>
</ul>
</div>
<ul>
<li>Outside Item</li>
<li>Another Outside Item</li>
</ul>
</body>
</html>
Only the list items inside the container div are styled with green backgrounds and white text. The list items outside the container remain unstyled, showing the specificity of the chained direct child selector.
Conclusion
The greater-than sign (>) in CSS is a powerful selector for targeting only direct children of an element. It provides precise control over styling by excluding deeper nested elements, making it essential for creating specific and maintainable CSS rules.
