DEV Community

loading...
Cover image for Centering in modern CSS

Centering in modern CSS

mr_eis profile image Marius Eisenbraun ・1 min read

Centering stuff in a layout sounds like a usual thing. Everyone does it in designs, sketches or even Word documents.

But for the web it was complicated for years to centering content or HTML elements - especially in vertical direction.

The good ol' time

You could use things like display: table or later positioning + transform: translate(). It works! But explaining that behavior to new developers was always a bit uncomfortable. Because the newbie and the teacher both got that feeling:

"There must be a better solution!"

Well, it is!

modern CSS

In the CSS-era of flexbox and grid both display types offer an easy solution to this one big question:

.container-element {
  display: grid; // or flex!
  align-items: center;
  justify-content: center;
}

What ever element will but put inside that container, it will be centered. In both directions!

In addition there are two more benefits:

  1. No fix values, means: responsive by default!
  2. Not only centering child elements but also centering the pure text content of the container

a short demo using both:

Codepen: https://codepen.io/mreis/pen/WNbXPeB

Discussion (6)

pic
Editor guide
Collapse
darival profile image
Darival

There is also another way to do this with grid.

.grid--container {
display: grid;
place-content:center;
}

Collapse
mr_eis profile image
Marius Eisenbraun Author

Yes, that should work to!

For the once, who doesn't know:
place-content is the shorthand for align-content and justify-content.

align-content has a different behavior than align-items. I guess, I never used align-content, so i didn't want to mention a technique i haven't tested in real life.

Did you use align-content? Why / in what context?

Collapse
russellbishop profile image
Russell Bishop

If you have just one child element to center, you can set flex on the parent and margin auto on the child.

Collapse
mr_eis profile image
Marius Eisenbraun Author

Yeah, that's a very nice solution, too!

For myself, I like to use the container to take care of its inner layout. That's why I wrote about this approach.

Collapse
adamwojnicki profile image
Adam Wojnicki

In the first example I'd pick flex. In case somebody expects IE compatibility.

Collapse
mr_eis profile image
Marius Eisenbraun Author

In general, both display types result in the same rendering.

If compatibility is needed, flexbox is maybe the better solution.
IE11 supports grid too, but has many bugs. So I'm not sure without testing, if this solution would work as expected.