I Finally Understood This Magic CSS Snippet


I used to drop this snippet into every project:

body {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
Enter fullscreen mode

Exit fullscreen mode

It always centered my content perfectly — both vertically and horizontally —
but honestly, I had no idea why it worked.

So I finally decided to dig in.



What It Does?

This snippet centers whatever is inside the both *vertically and horizontally * in the viewport.
It’s a simple, powerful pattern that works consistently across screen sizes.



🧩 Step-by-Step Breakdown

min-height: 100vh;

The vh unit stands for viewport height, where 100vh equals 100% of the browser window’s height.

This line ensures that even if the content is small, the element always stretches to fill the full height of the viewport, making vertical cantering possible.

display: flex;

This is the magic switch that turns the into a flex container.
Once that happens, its direct children become flex items, which can be positioned and aligned easily using Flexbox properties.



Key Insight

Why is making the a flex container so important?
Because it changes how the browser lays out elements.

By default, the uses the block layout model — elements simply stack one below another.
If you wanted to center something before Flexbox, you had to rely on awkward tricks like margins, absolute positioning, or transforms.

Flexbox fixes all that. It gives you clean, predictable control over alignment and spacing.



Why It Centres So Perfectly

Once is a flex container, these two properties do the heavy lifting:

justify-content: center; → centres items horizontally.

align-items: center; → centres items vertically.

Together, they place your content exactly in the middle of the viewport — with no hacks, no guesswork.



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *