Pseudo-Classes/Elements

CSS :first-child

Selecting First Child Elements

CSS :first-child targets first children, with :last-child for last.

Understanding the :first-child Selector

The :first-child pseudo-class in CSS is used to select the first child element within a parent element. This selector is particularly useful when you want to apply specific styles to the first item in a list, table row, or any other container with multiple children.

Basic Syntax of :first-child

The syntax for using the :first-child selector is straightforward. You simply append :first-child to the element you want to target. Here's a basic example:

In this example, the first <li> element within any <ul> will be styled with a red text color.

Practical Example: Styling a List

Let's consider a scenario where you have an unordered list, and you want to highlight the first item differently from the others:

In this HTML snippet, the first list item, "Home", will have bold text and a light gray background, distinguishing it from the other items.

Comparison with :last-child

While :first-child targets the first child element, :last-child is used to target the last child element within a parent. These selectors can be combined to apply styles to both the first and last elements.

In this example, the first <li> will have bold text, while the last <li> will be italicized. This demonstrates how you can use both selectors to style different elements within the same parent.

Limitations of :first-child

It's important to note that :first-child only selects the first child of its parent, regardless of the type of element. If you only want to select the first instance of a particular type of element, you might need to use :first-of-type instead.

In this code, the first <p> within a <div> (not necessarily the first child) will have blue text. This contrasts with :first-child, which would select any first child regardless of type.

Previous
:not