Nowadays, I choose Tailwind CSS as my goto CSS framework. And today, I’ll show you how to center div elements with Tailwind CSS quickly.
We’ll learn how to center a div in the middle of the screen using two methods:
- center a div element with Tailywind using Flexbox CSS
- use CSS Grid to center an element
There isn’t a clear wrong or right choice between these two methods. Generally, CSS grid should be used for the high-level layout and Flexbox CSS for lower-level HTML elements, such as details.
In the Codepen demo below, we’ll use the same CSS structure, so you can see the difference between the Tailwind Grid center and Tailwind Flexbox center.
1. Tailwind center div with CSS Grid
We’ll start by using grid center to make a div element horizontally and vertically centered on a page.
<div class="grid h-screen place-items-center">Centered using Tailwind Grid</div>
Can you believe these Tailwind classes is all we need to center vertically and horizontally?
Let’s explore the classes.
grid
: Gives the element a display: grid css propertyplace-items-center
: Gives it the center value on the place-items property, centeringh-screen
: Sets the 100vh (screen-height) as the height
Demo Tailwind grid center
This CSS code will perfectly center the div element horizontally and vertically on the page:
See the Pen Grid center content using Tailwind CSS by Chris Bongers (@rebelchris) on CodePen.
Looking for a CSS Grid centered version?
2. Tailwind center div with CSS Flexbox
A second option to center in Tailwind is to use CSS Flexbox for the HTML element. The method is pretty similar, but we have to specify the horizontal and vertical alignment with Flexbox.
Let’s see how centering looks with Flexbox:
<div class="flex items-center justify-center h-screen">
Centered using Tailwind Flex
</div>
As you can see, the div alignment looks similar to the first example but with an extra variable.
flex
: Adds the display: flex CSS propertyjustify-center
: This centers the div horizontallyitems-center
: This centers the content verticallyh-screen
: Sets the 100vh (screen-height) as the height
The final CSS code will look like the following:
Example Tailwind flex center
See the Pen Flex center div using Tailwind CSS by Chris Bongers (@rebelchris) on CodePen.
Looking for the CSS Flex center article?
Thank you for reading the tutorial, let’s connect!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter