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:
- No fix values, means: responsive by default!
- 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
Top comments (6)
There is also another way to do this with grid.
.grid--container {
display: grid;
place-content:center;
}
Yes, that should work to!
For the once, who doesn't know:
place-content
is the shorthand foralign-content
andjustify-content
.align-content
has a different behavior thanalign-items
. I guess, I never usedalign-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?If you have just one child element to center, you can set flex on the parent and margin auto on the child.
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.
In the first example I'd pick flex. In case somebody expects IE compatibility.
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.