In this tutorial, you'll learn how to use TailwindCSS to horizontally and vertically center a <div>
within the full viewport of a browser. TailwindCSS is a utility-first CSS framework packed with classes like flex, padding, margin, etc., that can be composed to build any design directly in your markup.
Before you begin, make sure your project is setup to use TailwindCSS. You can include TailwindCSS in your project by following the installation guide on the official TailwindCSS website.
Let's examine the original code snippet:
<>
<div>
center this div
</div>
</>
In the original JSX code, there's a <div>
element that we want to center on the page, but it is not centered by default.
Now, let's look at the updated code with the TailwindCSS classes applied:
<div className='flex items-center justify-center h-screen w-screen'>
<div>
center this div
</div>
</div>
-
Outer
<div>
with Tailwind Classes:+ <div className='flex items-center justify-center h-screen w-screen'>
flex
: This class applies the CSS propertydisplay: flex;
. Flexbox is a layout mode intended to arrange children linearly, either as rows or columns.items-center
: This class aligns the flex items (children of the flex container) in the center vertically. It effectively sets the CSS propertyalign-items: center;
.justify-center
: This aligns the flex items at the center of the container along the main axis (horizontally forflex-direction: row
, which is the default). It sets the CSS propertyjustify-content: center;
.h-screen
: This sets the height of the container to the full height of the viewport (height: 100vh;
).w-screen
: Similar toh-screen
, this sets the width of the container to the full width of the viewport (width: 100vw;
).
These Tailwind classes collectively center the child
<div>
both vertically and horizontally in the viewport. -
Child
<div>
:<div> center this div </div>
The content within this inner
<div>
remains the same, but due to the styling applied from its parent, it is now centered within the viewport.
With these changes in the code, when you load your application, you will see that the phrase "center this div" is perfectly centered on the screen both vertically and horizontally.
Using TailwindCSS to layout and style your application can be very efficient and effective, especially for responsive designs. The utility classes provided are straightforward and can be composed in various ways to achieve complex designs without leaving your HTML.
By following this simple tutorial, you've learned how to center a <div>
using a few utility classes provided by TailwindCSS. This pattern can be reused anywhere across your application where you need centered content.