CSS BASICS / LAYOUT
How to center a div
The parent is the outer box. The child is the box we want to move.
Center horizontally with margin: auto
Moves the child to the horizontal middle. It does not center vertically.
/* Give the child a width, then auto margins share the free space. */
.child {
width: 190px;
margin: 0 auto;
}
Remember:
margin: 0 auto
means top/bottom margin is 0 and left/right margins are automatic.
Center both ways with Flexbox
Make the parent a flex container. These two rules center its child horizontally and vertically.
/* Put these rules on the PARENT, not the child. */
.parent {
display: flex;
justify-content: center; /* horizontal */
align-items: center; /* vertical */
}
Remember: The parent needs some height for vertical centering to be visible.
Center both ways with CSS Grid
A compact alternative:
place-items: center
centers the child on both axes.
/* Put this on the PARENT. */
.parent {
display: grid;
place-items: center;
}
Remember: Like Flexbox, the parent needs height if you want to see vertical centering.
Center with absolute positioning
Place the child at the parent's midpoint, then shift it back by half its own size.
/* Parent establishes the positioning area. */
.parent {
position: relative;
}
/* These rules go on the CHILD. */
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Remember:
The parent needs
position: relative
so the child is positioned inside it.