Centering content makes your webpage look neat and balanced. The container utility helps keep your content in the middle with space on the sides.
Container utility for centering in Tailwind
<div class="container mx-auto">
<!-- Your content here -->
</div>container sets a max width that changes with screen size.
mx-auto adds automatic left and right margins to center the container horizontally.
<div class="container mx-auto">
<p>This content is centered and has max width.</p>
</div>px-4 gives horizontal padding so content doesn't touch edges on small screens.<div class="container mx-auto px-4">
<p>This container has padding on left and right for small screens.</p>
</div>container with max-w-lg to limit width further.<div class="container mx-auto max-w-lg">
<p>This container is centered but limited to a smaller max width.</p>
</div>This example shows a simple webpage with a header, main content, and footer. Each section uses the container mx-auto classes to center content and keep it from stretching too wide. Padding and background colors make it look clean and easy to read.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Centered Container Example</title> <script src="https://cdn.tailwindcss.com"></script> </head> <body class="bg-gray-100"> <header class="bg-blue-600 text-white p-4"> <h1 class="container mx-auto text-center text-2xl font-bold">Welcome to My Website</h1> </header> <main class="container mx-auto px-4 mt-8 bg-white p-6 rounded shadow"> <p>This container is centered on the page with some padding and a max width that adjusts on different screen sizes.</p> </main> <footer class="bg-blue-600 text-white p-4 mt-8"> <p class="container mx-auto text-center">Ā© 2024 My Website</p> </footer> </body> </html>
The container class automatically changes max-width at different screen sizes for a responsive design.
Always add mx-auto to center the container horizontally.
Use padding classes like px-4 inside the container to prevent content from touching screen edges on small devices.
The container utility sets a max width that adapts to screen size.
Use mx-auto to center the container horizontally.
Combine with padding classes for better spacing on small screens.