Tailwind CSS: Center an Element inside a Div

Updated: March 3, 2023 By: A Goodman One comment

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:

You can also check out our CSS category page for the latest tutorials and examples.

Subscribe
Notify of
guest
1 Comment
Inline Feedbacks
View all comments
woto
woto
2 years ago

Thanks!

Related Articles