0

I understand "margin: 0 auto" + "display: block" can centering elements such as div or img but i can't understand the logic behind it. All we saying is: 1. The element have zero space between it borders to the "outside". 2. you "catch" all the line.

I really can't understand why it centering elements.

Thank you !!!

lir
  • 21
  • 4
  • What is specified here is automatic left/right margins and zero top/bottom margins. The automatic `auto` part is what causes the centering. – Henrik Oct 13 '19 at 06:58

3 Answers3

0

You can set the margin property to auto to horizontally center the element within its container.

The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.

-1

margin: 0 auto means 0 vertical margin and an automatic horizontal margin. "automatic horizontal margin" basically means generating automatic centering margins (relative to parent).

display: block ensures that it's handled as a block element and not an inline element.

You can sort of think of auto as meaning "center"; (though there might be exceptions where you wouldn't want to always think of it that way, not sure.)

Dave Cousineau
  • 12,154
  • 8
  • 64
  • 80
  • But why it doesn't work without "display:block" ? @Dave Cousineau – lir Sep 29 '19 at 17:41
  • @lir inline elements behave differently. if the element is already a block element, like a `div`, then you shouldn't need `display: block`. if it's something like a `span`, then certain kinds of formatting won't work, or will work differently. inline elements *kind of* work like sentences (in terms of formatting), and block elements *kind of* work like paragraphs. – Dave Cousineau Sep 29 '19 at 18:54
-2

Beacause browser calculates margin-left and margin-right for you and spaces it evenly.

enter link description here