0% completed
CSS pseudo-classes allow you to style specific elements based on their position in a list. With pseudo-classes like :first-child
and :last-child
, you can easily target the first or the last item in a container. This technique is useful when you want to give unique styling to these elements without adding extra classes or IDs.
:first-child
: Targets the first element among its siblings.:last-child
: Targets the last element among its siblings.These selectors are often used with list items, divs, and other elements that are repeated in a container.
Follow the code block below to target the first and last elements using CSS:
/* Target the first child element */ selector:first-child { property: value; } /* Target the last child element */ selector:last-child { property: value; }
Explanation:
:first-child
:
:last-child
:
In this example, we create an unordered list and style the first item with a different background color and the last item with a distinct font style.
Explanation:
In this example, we target the first <div>
in a container and apply a special border to differentiate it from others.
Explanation:
:first-child
, the first <div>
inside the container gets a thicker, orange border to make it unique.This lesson demonstrates how to target the first or last element in a list using pseudo-classes. By utilizing :first-child
and :last-child
, you can apply unique styles to these elements, creating clear visual hierarchies and enhancing the overall user experience—all without extra HTML classes or JavaScript.
.....
.....
.....