Centering a div made easy with Tailwind CSS
khazifire
Posted on January 30, 2022
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>
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>
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.
Posted on January 30, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.