Solution
How to center a div?
GreatFrontEnd has better questions!
We don't create questions because GreatFrontEnd already has the best possible library of questions and we recommend the same to our community.
This is our founder's favorite question to ask in an interview with an intern or a fresh graduate. Though it might seem simple, the answer to this question can tell a lot about your CSS fundamentals.
There are various ways to solve this problem. But two of the most common ones are:
- Using Absolute positioning
- Using Flexbox
We will solve this question with both regular CSS and Tailwind CSS.
Absolute positioning (Regular CSS)
Depending on how confident you are, you might write something like this:
And the following CSS:
Except it will only center the div horizontally. What is missing? The height on the parent div.
So, then you would immediately add a height of 100vh
on the parent div.
Alright, the div
seems to be centered but here comes the tricky part. Why is there a vertical scroll bar now?
The issue is evident when you add background colors to the divs.
Did you notice it? There seems to be some kind of margin on the body
element (inspect it with browser tools).
This is where we need to bring in a CSS reset or normalize.
A very minimal CSS reset would be something like this:
Now the div
is really centered with no side effects. Next, let us try the Flexbox solution.
Flexbox (Regular CSS)
We will preserve the CSS reset used above. Our index.html
file would also remain the same as the previous solution.
How is this different from the previous solution? Put up some background colors and you will see the difference. Now, the height of the centered div
is 100% of the parent div. Whereas with absolute positioning, the height of the centered div
was just the height of the text.
You would seldom center something horizontally and vertically across the entire screen. In most cases, you work with a smaller height.
Absolute positioning (TailwindCSS)
Let us try the same solution of Absolute Positioning
with Tailwind CSS.
We need to bring in the Tailwind CSS CDN first.
Then we again wrap the div
to be centered in another div
. Then add the respective Tailwind CSS classes.
But wait this time, there is no vertical scroll bar and we did not apply any reset or normalize. Why? Technically, the Tailwind CSS CDN already includes a CSS normalization. So, we are good.
Flexbox (TailwindCSS)
Now, we will try the same solution of Flexbox
with Tailwind CSS.
GreatFrontEnd has better questions!
We don't create questions because GreatFrontEnd already has the best possible library of questions and we recommend the same to our community.
Last updated on