Vertical centering in CSS with margin: auto

Published on in CSS and CSS for JS Devs course

margin: auto is not only for horizontal centering.

margin: auto normally centers a block element only horizontally. To achieve vertical centering, it's common to reach for e.g. flexbox.

Turns out that margin: auto can in some cases center vertically as well. The element must also have:

  • position: absolute or position: fixed
  • top: 0 and bottom: 0
  • an explicit height (e.g. height: 200px).

This can be very useful for modals.

Note that for only vertical centering, only margin-top and margin-bottom need to be set to auto; margin-right and margin-left can be anything. This is similar to horizontal centering: only margin-right and margin-left need to be set to auto; margin-top and margin-bottom can be anything.

See an example on flems.io.

I learned this from Josh W Comeau's CSS for JavaScript developers course (Module 2).