CSS for Web Development

0% completed

Previous
Next
Targeting the first or last element in a list

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.

Syntax

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:
    • Styles the first element among a group of sibling elements.
  • :last-child:
    • Styles the last element among its siblings.

Example 1: Styling the First and Last Items in an Unordered List

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.

HTML

. . . .

Explanation:

  • First Item:
    • The first list item has a different background color, making it stand out from the rest.
  • Last Item:
    • The last list item is styled with bold text for added emphasis.

Example 2: Applying Unique Border to the First Element in a Container

In this example, we target the first <div> in a container and apply a special border to differentiate it from others.

HTML

. . . .

Explanation:

  • First Div:
    • Using :first-child, the first <div> inside the container gets a thicker, orange border to make it unique.
  • Outcome:
    • The container shows a visual hierarchy, emphasizing the first element among the siblings.

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.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next