CSS Basic
CSS :first-child Selector
Photo Credit to CodeToFun
🙋 Introduction
The :first-child
selector in CSS is used to target the first child element of its parent.
This pseudo-class allows you to apply specific styles to the very first child element within a parent container, making it useful for creating unique styling rules based on element position.
💡 Syntax
The signature of the :first-child
Selector is as follows:
selector:first-child {
/* CSS properties */
}
In this syntax:
- selector represents the parent element.
:first-child
targets the first child element of that parent.
📝 Example
Here is an example of how to use the :first-child
selector in CSS:
☠️ HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS :first-child Selector Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<ul>
<li>First Item</li>
<li>Second Item</li>
<li>Third Item</li>
</ul>
</body>
</html>
🎨 CSS
/* Style for the first child of any parent */
ul > li:first-child {
color: red;
font-weight: bold;
}
In this example:
- The first <li> element within the <ul> will be styled with red text and bold font weight.
💬 Usage Tips
- The
:first-child
selector targets the very first child of a specified parent. Ensure the element you want to style is indeed the first child within its parent element. - Combine
:first-child
with other selectors to create more specific rules. For instance, div > p:first-child targets the first <p> child within a <div>.
⚠️ Common Pitfalls
- The
:first-child
pseudo-class only applies to the very first child element of a parent, regardless of element type. For example, if the first child is a <div>, it will be selected even if the next sibling is a <p>. - Ensure the targeted element is the first child of its parent. If there are any other elements (even if they are empty or invisible) before it, :first-child will not apply.
🎉 Conclusion
The :first-child
selector is a versatile tool in CSS for applying styles to the first child element of a parent container.
By using this pseudo-class, you can create distinctive designs and enhance the visual hierarchy of your content. Proper use of :first-child
helps in maintaining a clean and organized stylesheet while targeting specific elements based on their position in the document structure.
👨💻 Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (CSS :first-child Selector), please comment here. I will help you immediately.