3

Why does the div display property inline-block move the paragraph to left which was centered by margin:0 auto without display property.

.content
{
    padding: 20px;
    margin: 0 auto;
    display: inline-block;
    width: 900px;
    height: 2000px;
}

The content is the class id of the div which has some paragraph inside it. When I add display: inline-block the paragraph is moving to the left side. Why is it so?

https://jsfiddle.net/3h1wwgy6/1/

Sreeraj Chundayil
  • 5,548
  • 3
  • 29
  • 68

2 Answers2

3

DIV as display:block(block level element) has characteristic/behavior to occupy entire page width. So when you assign auto for margin-left and margin-right, it automatically takes up the available space equally on both sides. So the element will be centered based on width of its parent element.

When you change the display property of a DIV to display:inline-block. It takes up the best of both worlds (block & inline) i.e., You can use a definitive margins, padding like block elements AND it can follow the normal HTML layout flow like any inline element e.g., span or anchor.

So when you say auto to an inline-block, the default automatic behavior for inline-block is to follow the normal flow of the document (i.e., 0px).

Official definition for auto :

Auto margins

Depending upon the circumstances, provision of an auto value instructs the browser to render a margin according to the value provided in its own stylesheet. However, when such a margin is applied to an element with a meaningful width, an auto margin instead causes all of the available space to be rendered as whitespace.

David Chelliah
  • 1,319
  • 1
  • 13
  • 24
2

Use text-align: center on its parent div to center a div with display:inline-block. As @David Chelliah said, display: inline-block makes it act like an inline-element.

Sam Malayek
  • 3,595
  • 3
  • 30
  • 46