CSS first child
Created By: chatGPT
The
:first-child
pseudo-class in CSS allows you to select the first child of a parent element. This is particularly useful when you want to style the first element differently than others. The :first-child
selector applies to any type of element, as long as it's the first of its parent. It's worth noting that the selected element must be an actual child, not just a descendant.p:first-child {
color: blue;
font-weight: bold;
}
If you have a list, for example, you might want to make only the first list item stand out. You can achieve this with the following code:
ul li:first-child {
background-color: yellow;
font-size: 1.2em;
}
To see the practical use of
:first-child
, consider the following HTML structure and associated styles:<style>
div p:first-child {
font-style: italic;
}
</style>
<div>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
</div>
In this example, the first paragraph inside the
div
will display in italic style because of the :first-child
selector. If you want to apply styles to, say, the first header in a set, you can do this as well:h1:first-child {
color: red;
}
Keep in mind that
:first-child
will only select an element if it is the first child of its parent. If you have a sibling, like this:<div>
<header>A header</header>
<p>This paragraph is the first child.</p>
<p>This paragraph is not the first.</p>
</div>
In this scenario,
header:first-child
would not apply because the header is not the first child of the div
. The first child is actually the paragraph. Hence, careful consideration of your structure is necessary when using :first-child
.div :first-child {
margin-bottom: 20px;
}