CSS

Why isn’t Flexbox centering my item?

A button can look stuck at the top even when align-items: center is working perfectly. First, draw a border around its parent. The button can only be centered inside that box. If the box is exactly as tall as the button, there is no spare height to distribute.

Make the container visible

Paste this example into an HTML file and open it. The dashed border shows the area Flexbox controls. The button sits in its center.

<style>
  .stage {
    display: flex;
    min-height: 12rem;
    justify-content: center;
    align-items: center;
    border: 2px dashed rebeccapurple;
  }
</style>

<div class="stage">
  <button>Start round</button>
</div>

Now remove only min-height: 12rem. The border collapses around the button vertically. The button still has room to move left and right because the block container fills the available width. That difference explains why horizontal centering often looks fine while vertical centering appears broken.

Follow the main axis

justify-content distributes available space along the main axis. align-items sets alignment on the cross axis. The container’s flex-direction determines which axis is the main one.

In the example’s default horizontal writing mode, row places the main axis horizontally. Change the direction to column and the main axis runs vertically. To see which property is doing the work, keep the minimum height and try this override.

.stage {
  flex-direction: column;
  justify-content: flex-end;
  align-items: center;
}

Predict where the button will land before refreshing. It finishes at the bottom center. Change just column back to row and it moves to the right center in a left-to-right document.

Check the element that owns the layout

In browser developer tools, select the button and inspect its immediate parent. A common source of confusion is a wrapper between the flex container and the item you want to move. Flexbox positions the wrapper. The button inside still follows the wrapper’s layout.

For a single row, changing align-content is another easy dead end. That property distributes extra cross-axis space between lines in a wrapping flex container, while align-items controls items within a line. Start with one parent, one child, a visible border, and a single axis change. Then add the rest of your layout back. MDN’s guide to aligning flex items

← All coding guides