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-of-type Selector
The CSS :only-of-type pseudo-class selector is used to style elements that are the only child of their specific type within their parent container. It targets elements that have no siblings of the same element type.
Syntax
element:only-of-type {
/* CSS properties */
}
Example: Basic Usage
The following example demonstrates how :only-of-type selects paragraph elements that are the only <p> element within their parent −
<!DOCTYPE html>
<html>
<head>
<style>
p:only-of-type {
background: orange;
color: white;
padding: 10px;
border-radius: 5px;
}
</style>
</head>
<body>
<div>
<p>This is demo text 1.</p>
</div>
<div>
<p>This is demo text 2.</p>
<p>This is demo text 3.</p>
<p>This is demo text 4.</p>
</div>
</body>
</html>
Only the first paragraph ("This is demo text 1.") appears with an orange background and white text, as it is the only paragraph element in its parent div. The other paragraphs remain unstyled.
Example: Different Element Types
This example shows how :only-of-type works with different element types −
<!DOCTYPE html>
<html>
<head>
<style>
h2:only-of-type {
color: blue;
border-bottom: 2px solid blue;
}
img:only-of-type {
border: 3px solid red;
padding: 5px;
}
</style>
</head>
<body>
<div>
<h2>Single Heading</h2>
<p>Some content</p>
</div>
<div>
<h2>First Heading</h2>
<h2>Second Heading</h2>
</div>
</body>
</html>
The first h2 element ("Single Heading") appears in blue with a blue underline, as it's the only h2 in its parent div. The other h2 elements remain unstyled because they have siblings of the same type.
Conclusion
The :only-of-type selector is useful for styling unique elements within containers. It helps target elements that stand alone among their element type, making it perfect for special formatting of singular content pieces.
Advertisements
