The :first-child selector in CSS targets the first child element of a specific parent element. It’s a powerful tool for styling the first occurrence of an element within a group.
Syntax
parent-element :first-child {
/* Styles for the first child */
}
Example
Let’s say we have an unordered list (UL) with multiple list items (LI). We want to style the first list item differently.
<ul>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ul>
To style the first list item, we can use the :first-child selector:
ul li:first-child {
color: blue;
font-weight: bold;
}
This will apply the specified styles (blue color and bold font weight) only to the first list item within the unordered list.
Key Points to Remember
- Specificity: The
:first-childselector has a specificity of 1, which is relatively low. If other selectors with higher specificity are applied to the same element, they may override the:first-childstyles. - Combinations: You can combine
:first-childwith other selectors to create more targeted styles. For example,p:first-childwill style the first paragraph element within its parent. - Sibling Selectors: While
:first-childtargets the first child, you can use the:nth-child(1)selector to target the first child, the:nth-child(2)selector for the second, and so on.
Additional Tips
- Use with caution: Overusing
:first-childcan lead to complex and hard-to-maintain stylesheets. - Consider other approaches: In some cases, using CSS classes or ID selectors might be a more efficient and maintainable solution.
- Test your styles: Always test your styles in different browsers to ensure cross-browser compatibility.