This short and straight-to-the-point article shows you how to vertically and horizontally center an element inside a <div> element with TailwindCSS.
Center an Element Vertically
To vertically center an element, just use Tailwind’s flex and items-center utilities, like this:
<body>
<div class="w-96 h-96 bg-blue-500 flex items-center">
<div class="w-48 h-48 bg-green-500"></div>
</div>
</body>
Screenshot:
Center an Element horizontally
You can easily center an element horizontally by using Tailwind’s flex and justify-center classes, like this:
<body>
<div class="w-96 h-96 bg-blue-500 flex justify-center">
<div class="w-48 h-48 bg-green-500"></div>
</div>
</body>
Screenshot:
If you want to center both vertically and horizontally, then do as follows:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.tailwindcss.com"></script>
<title>KindaCode.com</title>
</head>
<body>
<div class="w-96 h-96 bg-blue-500 flex justify-center items-center">
<div class="w-48 h-48 bg-green-500"></div>
</div>
</body>
</html>
Screenshot:
Further reading:
- CSS: Flipping Card on Hover
- Displaying Toast Messages with Tailwind CSS
- Tailwind CSS: Grid examples (with explanations)
- Tailwind CSS + Font Awesome: Download Button Examples
- Most Popular Open-Souce CSS Frameworks
- CSS Flexbox: Make an Element Fill the Remaining Space
You can also check out our CSS category page for the latest tutorials and examples.
Thanks!