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
How to use a not:first-child selector in CSS?
The CSS :not(:first-child) selector combines the :not and :first-child pseudo-classes to select all elements except the first child of their parent. This is useful when you want to style all child elements except the first one.
Syntax
element:not(:first-child) {
/* CSS styles */
}
Method 1: Selecting Specific Child Elements
You can target specific elements within a parent container, excluding the first one
<!DOCTYPE html>
<html>
<head>
<style>
div p:not(:first-child) {
color: green;
font-size: 18px;
margin-top: 15px;
}
</style>
</head>
<body>
<h3>Styling all paragraphs except the first one</h3>
<div>
<p>First paragraph (no styling)</p>
<p>Second paragraph (styled)</p>
<p>Third paragraph (styled)</p>
</div>
</body>
</html>
The first paragraph appears in default black text, while the second and third paragraphs are displayed in green color with larger font size and top margin.
Method 2: Styling List Items
Apply styles to all list items except the first one
<!DOCTYPE html>
<html>
<head>
<style>
ul li:not(:first-child) {
color: blue;
font-weight: bold;
border-top: 1px solid #ccc;
padding-top: 10px;
}
</style>
</head>
<body>
<h3>Course Topics</h3>
<ul>
<li>HTML Basics</li>
<li>CSS Styling</li>
<li>JavaScript Programming</li>
<li>React Framework</li>
</ul>
</body>
</html>
The first list item appears in normal styling, while the remaining items are displayed in blue, bold text with a top border and padding.
Method 3: Universal Selector Application
Use the universal selector to apply styles to all elements except first children
<!DOCTYPE html>
<html>
<head>
<style>
*:not(:first-child) {
margin-top: 20px;
padding: 10px;
border-left: 3px solid #007acc;
}
body {
font-family: Arial, sans-serif;
margin: 20px;
}
</style>
</head>
<body>
<h3>Universal Not First Child Example</h3>
<p>First paragraph</p>
<p>Second paragraph</p>
<div>
<span>First span in div</span>
<span>Second span in div</span>
</div>
</body>
</html>
All elements except the first child of their respective parents display with top margin, padding, and a blue left border.
Conclusion
The :not(:first-child) selector provides an efficient way to apply styles to all child elements except the first one. This combination selector is particularly useful for creating consistent spacing, borders, or styling patterns in lists and content blocks.
