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
Usage of :first-child pseudo-class in CSS
The CSS :first-child pseudo-class is used to select and style an element that is the first child of its parent element. This selector only targets the very first child element, regardless of its type.
Syntax
selector:first-child {
property: value;
}
Example: Basic Usage
The following example demonstrates how :first-child selects the first paragraph inside a div element −
<!DOCTYPE html>
<html>
<head>
<style>
div > p:first-child {
text-indent: 25px;
color: blue;
font-weight: bold;
}
</style>
</head>
<body>
<div>
<p>First paragraph in div. This paragraph will be indented and styled.</p>
<p>Second paragraph in div. This paragraph will not be affected.</p>
</div>
<p>Paragraph outside div - not affected.</p>
<div>
<h3>Heading comes first</h3>
<p>This paragraph is not the first child, so it won't be styled.</p>
</div>
</body>
</html>
The first paragraph in the first div appears indented (25px), blue, and bold. The second paragraph and the paragraph in the second div (after the heading) remain unstyled with default formatting.
Key Points
- The
:first-childselector only matches the very first child element of a parent - If the first child is not the target element type, the selector won't match anything
- It's commonly used for removing margins from the first element or adding special styling
Conclusion
The :first-child pseudo-class is essential for targeting the first child element within a container. Remember that it selects based on position, not element type, so ensure the first child matches your selector.
Advertisements
