H1 won't center with margin: auto

According to Applied Visual Design: Center an Element Horizontally Using the margin Property, margin: auto; should center block elements horizontally.

I searched in MDN, and h1 is a block element.

Why with:

h1 { margin: auto; } isn’t centered but with `h1 { text-align: center; }, it is?


P.S. How to write multiline code?

Hello @Porphyrogennitos,
margin: auto will center a block level element within its container if you assign it a width.

Should I use text-align: center; or assign a width in a div that has the h1 nested?

I would recommend text-align: center;.

1 Like