First-child and last-child targeting helps you style the first or last item in a group differently. This makes your design clearer and more organized.
0
0
First-child and last-child targeting in Tailwind
Introduction
You want the first item in a list to have a different background color.
You want the last button in a group to have rounded corners.
You want to add extra space only before the first paragraph.
You want to highlight the first or last menu item in navigation.
You want to remove the border from the last item in a list.
Syntax
Tailwind
first:<utility> last:<utility>
Use first: before any Tailwind utility to style the first child element.
Use last: before any Tailwind utility to style the last child element.
Examples
The first list item text will be red.
Tailwind
<li class="first:text-red-500">Item 1</li> <li>Item 2</li>
The last button will have rounded corners.
Tailwind
<button>Save</button>
<button class="last:rounded-lg">Cancel</button>The first paragraph will have a top margin.
Tailwind
<p class="first:mt-4">Paragraph 1</p> <p>Paragraph 2</p>
Sample Program
This example shows a list where the first item has a light blue background and the last item has a light green background. The middle item has no special background. Borders separate the items.
Tailwind
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>First and Last Child Tailwind Example</title> <script src="https://cdn.tailwindcss.com"></script> </head> <body class="p-6"> <ul class="border border-gray-300 max-w-sm mx-auto"> <li class="first:bg-blue-100 last:bg-green-100 p-4 border-b border-gray-200">First item</li> <li class="p-4 border-b border-gray-200">Middle item</li> <li class="last:bg-green-100 p-4">Last item</li> </ul> </body> </html>
OutputSuccess
Important Notes
Make sure your HTML elements are siblings for first: and last: to work correctly.
You can combine these with other Tailwind utilities for more effects.
Use browser DevTools to inspect and test your styles live.
Summary
first: targets the first child element to style it differently.
last: targets the last child element to style it differently.
These help make lists and groups look neat and clear.