Layout with Flexbox and GridLesson 2.3
How to center elements vertically and horizontally in Tailwind
flex centering, grid place-items-center, absolute centering, margin auto, translate centering, full-screen centering, button centering
Centering Elements in Tailwind
Three dominant centering patterns: Flexbox for most cases, Grid for full-container, absolute positioning for overlays.
Flexbox centering (most common)
<!-- Horizontally centered -->
<div class="flex justify-center">
<span>Centered</span>
</div>
<!-- Both axes -->
<div class="flex items-center justify-center h-screen">
<div class="bg-white p-8 rounded-xl shadow">Modal</div>
</div>Grid centering
<div class="grid place-items-center min-h-screen">
<div>Perfectly centered</div>
</div>Absolute centering (for overlays)
<div class="relative">
<div class="absolute inset-0 flex items-center justify-center">
<span class="text-white font-bold">Overlay</span>
</div>
<img src="hero.jpg" class="w-full" />
</div>Block horizontal centering
<div class="max-w-2xl mx-auto px-4">
<!-- Content centered with max-width constraint -->
</div>mx-auto on a block element with an explicit width or max-width centers it horizontally. This is the standard pattern for page content containers.
