How do I center a div?

Ask Question
Asked 3 days agoViewed 2.8k times
42

The eternal question. What is the modern, reliable way to center a block both horizontally and vertically?

SA
asked 3 days agoSofia Alvarez5,306

4 Answers

  • Absolute + translate(-50%,-50%) when you must position over other content.

    LO
    answered 2 days agoLiam OConnor2,940
  • Accepted answer

    Flexbox: display:flex; justify-content:center; align-items:center; on the parent does it cleanly.

    PN
    answered 3 days agoPriya Nair6,386
  • Grid one-liner: display:grid; place-items:center; — even shorter than the flexbox version.

    MW
    answered 3 days agoMarcus Webb7,334
  • For a fixed-width block, margin-inline:auto still works for horizontal centering.

    SA
    answered 3 days agoSofia Alvarez5,306

Your Answer