Dividing utilities between children helps you control how space and styles apply to each child element inside a container. It makes your layout neat and organized.
0
0
Divide utilities between children in Tailwind
Introduction
You want to give equal space to each item inside a box.
You want to add different margins or padding to each child element.
You want to style only the first or last child differently.
You want to create a row or column layout where children share space evenly.
You want to add borders or backgrounds to specific children.
Syntax
Tailwind
parent-class > :child-selector { @apply utility-classes; }Use
:first-child, :last-child, or :nth-child(n) to target specific children.Tailwind's
@apply lets you add utility classes inside CSS for children.Examples
Each child takes equal space in a row using
flex-1.Tailwind
<div class="flex"> <div class="flex-1">Child 1</div> <div class="flex-1">Child 2</div> <div class="flex-1">Child 3</div> </div>
Adds horizontal space between each child button.
Tailwind
<div class="space-x-4"> <button>Button 1</button> <button>Button 2</button> <button>Button 3</button> </div>
Styles first and last child differently using Tailwind inside CSS.
Tailwind
<style>
.parent > :first-child {
@apply text-red-500;
}
.parent > :last-child {
@apply text-blue-500;
}
</style>
<div class="parent">
<p>First child</p>
<p>Middle child</p>
<p>Last child</p>
</div>Sample Program
This example shows three children inside a flex container. Each child has a different background color and padding using Tailwind utilities applied to specific children.
Tailwind
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Divide Utilities Between Children</title> <script src="https://cdn.tailwindcss.com"></script> <style> .container > :first-child { @apply bg-green-200 p-4; } .container > :nth-child(2) { @apply bg-yellow-200 p-4; } .container > :last-child { @apply bg-red-200 p-4; } </style> </head> <body class="flex justify-center items-center min-h-screen bg-gray-50"> <div class="container flex space-x-4"> <div>Child One</div> <div>Child Two</div> <div>Child Three</div> </div> </body> </html>
OutputSuccess
Important Notes
Use space-x-* or space-y-* utilities on the parent to add consistent spacing between children.
Target children with CSS selectors like :first-child or :nth-child(n) combined with @apply for custom styling.
Remember to use semantic HTML and keep your layout accessible by using proper roles and keyboard navigation if needed.
Summary
Dividing utilities between children helps control layout and style for each child element.
Use Tailwind's flex, spacing, and @apply with child selectors to style children differently.
This makes your design organized, responsive, and easy to maintain.