0
0
CSSmarkup~5 mins

First-child and last-child in CSS

Choose your learning style9 modes available
Introduction

These selectors help you style the very first or very last item inside a group. It makes your page look neat and organized.

You want the first item in a list to have a special color.
You want the last paragraph in a section to have extra space below it.
You want to highlight the first button in a toolbar differently.
You want to remove the border from the last item in a menu.
You want to add a special icon only to the first or last element in a group.
Syntax
CSS
selector:first-child { property: value; }
selector:last-child { property: value; }

:first-child selects an element if it is the first child of its parent.

:last-child selects an element if it is the last child of its parent.

Examples
This makes the first list item red.
CSS
li:first-child {
  color: red;
}
This adds extra space below the last paragraph.
CSS
p:last-child {
  margin-bottom: 2rem;
}
The first button in a group gets a light blue background.
CSS
button:first-child {
  background-color: lightblue;
}
The last div inside a container has no border.
CSS
div:last-child {
  border: none;
}
Sample Program

This example shows a shopping list. The first item is highlighted with a green background and bold text. The last item has a pink background and italic text. The other items have a simple border and normal style.

CSS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>First-child and Last-child Example</title>
  <style>
    ul {
      list-style: none;
      padding: 0;
      max-width: 300px;
      margin: 1rem auto;
      font-family: Arial, sans-serif;
    }
    li {
      padding: 0.5rem;
      border: 1px solid #ccc;
      margin-bottom: 0.5rem;
      border-radius: 0.25rem;
    }
    li:first-child {
      background-color: #d1e7dd;
      font-weight: bold;
    }
    li:last-child {
      background-color: #f8d7da;
      font-style: italic;
    }
  </style>
</head>
<body>
  <main>
    <h1>Shopping List</h1>
    <ul>
      <li>Apples</li>
      <li>Bananas</li>
      <li>Carrots</li>
      <li>Dates</li>
    </ul>
  </main>
</body>
</html>
OutputSuccess
Important Notes

If the element is not the very first or last child of its parent, these selectors won't apply.

They only look at the position among siblings, not the type of element.

Use these selectors to improve user experience by visually grouping or separating items.

Summary

:first-child styles the first child element inside a parent.

:last-child styles the last child element inside a parent.

They help make lists and groups look clearer and more attractive.