DEV Community

khazifire
khazifire

Posted on • Originally published at khazifire.hashnode.dev on

Centering a div made easy with Tailwind CSS

Somehow centering a div is a problem that most people face, especially beginners getting started with web development. I have been working with Tailwind CSS and I wanted to quickly show you how to center a div using Tailwind.

Introduction

We will be exploring two methods of centering a div with Tailwind CSS. There is no right and wrong choice, so feel free to use whichever method you feel most comfortable using. Lets dive in!

1. Centering a div using Flex in Tailwind

We will start by using flex to center a div vertically and horizontally on a page. But before that, if you have not integrated Tailwind within your html project, check my previous article for a quick run through on how you can add tailwind to your html project.

<div class="flex justify-center items-center h-screen">
      Centered using flex
</div>

Enter fullscreen mode Exit fullscreen mode

Lets break down what we just did:

  • Flex: adds the CSS flex property (display:flex).
  • justify-center: used to center the div horizontally
  • items-center: used to center the content vertically
  • h-screen: not necessary but it sets the height of the div to 100vh (height:100vh).

That was easy right ? Lets move on to the second way of centering a div with Tailwind CSS.

2. Centering a div using Grid in Tailwind

A second option of centering an html element is by using Grid. This approach is very similar to flex, but with a few changes.

<div class="grid place-items-center h-screen">
  Centered using Grid
</div>

Enter fullscreen mode Exit fullscreen mode

Lets break down what we just did:

  • Grid: give the element a CSS grid property (display:grid).
  • place-items-center: places grid items on the center of their grid areas learn more
  • h-screen: sets the height of the div to 100vh (height:100vh).

Conclusion

I hope you can now center a div using either grid or flex😊. Thank you for reading. If you have any questions, feels free to reach me through twitter @khazifire. And don't forget to follow for more similar content.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay