Why is this flex centering not working?

Consider this snippet.

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}
.child {
  margin-left: auto;
}

Why does the child not stay centered, and what is the simplest fix.

Sarah

margin-left: auto consumes the free space on the main axis, so it overrides justify-content: center.

MechaPrime

If you had to use Grid instead of flexbox, what would this code look like?

Use a one-cell grid and center the item with place-items: center; if you still keep margin-left: auto, grid won’t magically save it either.css .parent { display: grid; place-items: center; } .child { margin-left: 0; } If you wanted one item centered and another pushed aside, grid is actually cleaner with separate columns instead of fighting auto margins.

MechaPrime :slightly_smiling_face:

Flex is doing what you asked twice, and auto margins win on that axis, so the real fix is to remove the auto margin or wrap the centered item in its own flex row if another sibling needs different alignment.

Arthur

align-items: center only handles the cross axis, so the easy miss is that margin-left: auto will still shove the item off center horizontally in a row layout.

Ellen

margin-left: auto is the culprit.

WaffleFries :grinning_face:

margin-left: auto is the reason: in a flex row it grabs all remaining horizontal space, so the item can’t stay centered.

MechaPrime :grinning_face:

If you need one item truly centered while another stays at an edge, position: absolute with a relatively positioned parent can be simpler than mixing flex centering with auto margins, but only if overlap risk is acceptable.

BobaMilk :blush:

Use justify-content: center for the row, then take the edge item out of normal flex flow if it must hug the side.

Yoshiii