制作 display:inline-block 将段落向左移动

Making display:inline-block moves the paragraph to left

为什么div显示属性inline-block将以margin:0 auto居中的段落向左移动而不显示属性.

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

content 是 div 的 class id,里面有一些段落。 当我添加 display: inline-block 时,该段落将移至左侧。为什么会这样?

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

DIV 因为 display:block(块级元素)有 characteristic/behavior 占据整个页面宽度。因此,当您为 margin-left 和 margin-right 分配 auto 时,它会自动 平均占用两侧的可用 space。因此该元素将根据其父元素的宽度居中。

当您将 DIV 的显示 属性 更改为 display:inline-block 时。它兼顾了两全其美(块和内联),即,您可以使用确定的边距,像块元素一样填充,并且它可以像任何内联元素(例如 span 或锚点)一样遵循正常的 HTML 布局流程。

所以当你对 inline-blockauto 时,inline-block 的默认自动行为是 遵循文档的正常流程(即 0px)。

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.

在父级 div 上使用 text-align: center 使 div 与 display:inline-block 居中。正如@David Chelliah 所说,display: inline-block 使其表现得像一个内联元素。