These selectors help you style the very first or very last item inside a group. It makes your page look neat and organized.
First-child and last-child in 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.
li:first-child { color: red; }
p:last-child { margin-bottom: 2rem; }
button:first-child { background-color: lightblue; }
div:last-child { border: none; }
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.
<!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>
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.
: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.