Photo by Luís Eusébio on Unsplash

Center A Div: Grid v/s Flex

Let’s learn it once and for all

Aditya Tyagi
2 min readFeb 26, 2024

--

If you are one of the developers/software engineers who are not able to center a div — don’t you worry, even Dan Abramov takes time to do that, and that is something when you are a software engineer at Meta and a coauthor of the Create React App and Redux!

Dan went through a mock interview with Ben Awad sometime back. Its fun to watch. The top rated comment was this:

Anyways, its pretty straightforward to center a div using tailwindcss.

Using Flex

<main class="flex flex-row justify-center items-center min-h-screen">
<section class="bg-black w-[50%]">
<h2>content</h2>
</section>
</main>

Brief: The result would have been same with flex-col as well. We are using min-h-screen for the parent to take 100% of the available height. Apart from that, justify-center is centering the child along horizontal axis while items-center is centering the child along vertical axis.

Using Grid

<main class="grid min-h-screen justify-items-center items-center">
<section class="bg-black w-[50%]">
<h2>content</h2>
</section>
</main>

Brief: Here, grid is used to create the layout. min-h-screen gives the main a minimum height of 100vh applying min-height: 100vh; Unlike flex, to center to align grid items along thier inline-axis, we use justify-items-center and items-center

Results for both:

--

--

Aditya Tyagi

Full Stack Engineer | JS, TS | NextJS, ReactJS | TailwindCSS | GraphQL