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
Selected Reading
Role of CSS :only-child Selector
The CSS :only-child selector targets elements that are the only child of their parent element. It styles elements when they have no siblings, making it useful for applying special formatting to isolated elements.
Syntax
element:only-child {
property: value;
}
Example: Styling Only Child Paragraphs
The following example demonstrates how the :only-child selector applies styles only to paragraphs that are the sole child of their parent −
<!DOCTYPE html>
<html>
<head>
<style>
p:only-child {
background-color: orange;
padding: 15px;
border-radius: 5px;
color: white;
font-weight: bold;
}
div {
margin: 20px 0;
border: 2px solid #ddd;
padding: 10px;
}
</style>
</head>
<body>
<h1>CSS :only-child Selector Demo</h1>
<div>
<p>I am the only paragraph in this div.</p>
</div>
<div>
<p>I am the first paragraph.</p>
<p>I am the second paragraph.</p>
<p>I am the third paragraph.</p>
</div>
<div>
<p>Another only child paragraph.</p>
</div>
</body>
</html>
The first and third div containers show paragraphs with orange background, white text, and rounded corners because they are only children. The middle div shows three unstyled paragraphs since they have siblings.
Example: Universal Only Child Selector
You can also use the universal selector to target any element that is an only child −
<!DOCTYPE html>
<html>
<head>
<style>
:only-child {
border: 3px solid #ff6b6b;
margin: 10px;
padding: 10px;
}
.container {
background-color: #f8f9fa;
margin: 15px 0;
padding: 10px;
}
</style>
</head>
<body>
<div class="container">
<span>Only span element</span>
</div>
<div class="container">
<h3>First heading</h3>
<h3>Second heading</h3>
</div>
<div class="container">
<button>Single button</button>
</div>
</body>
</html>
The span element and button receive red borders because they are only children, while the headings in the middle container remain unstyled as they have siblings.
Conclusion
The :only-child selector is perfect for styling elements that stand alone within their parent. It helps create clean, conditional formatting based on element relationships in the DOM structure.
Advertisements
