Structural pseudo-classes in CSS are powerful selectors that allow you to target elements based on their position and relationship within the document structure. Mastering these selectors enables more dynamic and precise styling without needing extra classes or IDs in your HTML.
:first-child
The :first-child
pseudo-class targets an element that is the first child of its parent. This is useful for applying specific styles to the very first element within any container.
Example 1: Styling the First Paragraph
/* Selects the first <p> element inside its parent */
p:first-child {
font-weight: bold;
color: #333;
}
Explanation
This code finds any <p>
element that is the immediate first child of its parent element and makes its text bold and dark grey. If the first child is not a paragraph, no styling is applied.
Example 2: Highlighting the First List Item
/* Targets the first <li> in any list */
li:first-child {
background-color: #f0f0f0;
border-left: 3px solid #007bff;
}
Explanation
This CSS applies a light grey background and a blue left border to the first list item (<li>
) within any ordered or unordered list.
Example 3: Adding a Special Margin to the First Section
/* Adds a top margin to the first <section> element */
section:first-child {
margin-top: 0;
}
Explanation
This rule removes the top margin from the very first <section>
element on the page, which can be useful for aligning content at the top of the viewport.
Example 4: Styling the First Column of a Table
/* Styles the first <td> in every table row <tr> */
tr td:first-child {
color: #555;
font-weight: bold;
}
Explanation
This targets the first table data cell (<td>
) in each table row (<tr>
), making its text bold and a different color to serve as a row header.
Example 5: A Unique Style for the First Article
/* Applies a top border to the first <article> in a container */
.article-container article:first-child {
border-top: 2px solid #ccc;
padding-top: 20px;
}
Explanation
This code selects the first <article>
element within an element that has the class .article-container
and adds a top border and padding.