按钮不会在块级容器中居中

Button does not get centered in block-level container

为什么放置在 flex 容器内的按钮使用 margin : 0px auto; 居中,但放置在普通容器内的按钮却不是?

此外,我该怎么做才能使按钮在普通容器中居中(我无法更改我的 HTML,因此 CSS 解决方案将不胜感激。)

.flex-container {
  display: flex;
  background: yellow;
}
.normal-container {
  background: green;
}
button {
  margin: 0px auto;
}
<div class="flex-container">
  <button>Button in flex</button>
</div>
<div class="normal-container">
  <button>Button in normal</button>
</div>

jsFiddle link : https://jsfiddle.net/r8h3d9wy/1/

text-align:center 在父级上,因为 inputs/buttons 是内联级别元素。

margin:0 auto 在 flex-containers 中起作用,因为这是对齐在 flex-items 上起作用的方式。它有效地消除了内联级别的性质并使其成为 flex-child。

.flex-container {
  display: flex;
  background: yellow;
  justify-content: center;
}
.normal-container {
  background: green;
  text-align: center;
}
<div class="flex-container">
  <button>Button in flex</button>
</div>
<div class="normal-container">
  <button>Button in normal</button>
</div>

在普通容器中,margin: 0px auto 仅应用于块元素。试试这个:

button {
    display: block;
    margin: 0px auto;
}

通常情况下,块元素的宽度默认为 100%。在这种情况下,这不是问题,因为您使用了一个按钮。否则,您必须设置宽度以使元素居中。

如果您检查 chrome 中的计算样式,您会注意到 flex 容器中的子元素将具有 display:block 而普通容器中的子元素将具有 display:inline-block .如果您将 display:block 添加到按钮的 CSS 中,它将在两个容器中居中。

对于行内元素,如 buttonmargin-left: automargin-right: auto 计算为 0。

10.3.1 Inline, non-replaced elements

The width property does not apply. A specified value of auto for left, right, margin-left or margin-right becomes a computed value of 0.

您可以通过以下方式使 button 元素居中:

  1. text-align: center 应用于父项 (demo),或
  2. 切换到按钮上的 display: block (demo)。

在 flex 容器中,您在 flex formatting context, which blockifies flex items and permits alignment with .

中工作

下面的 CSS 代码可以解决问题。我已经使用评论进行了解释。

.flex-container{
  display:flex;
  background:yellow;
}

.normal-container{
  background:green;
  text-align: center; /*aligns inline items to center.*/

button{
  margin : auto;
  display: inline; /* Not needed in this case as the button is an inline element naturally. However, if you have a block element, you would use this to make it an inline element. Explanation below. */
}

一个display:block元素占据父容器中它右边或左边的所有space。因此,margin:auto 什么都不做,因为没有余量。使它成为一个内联元素改变了这一点并释放了允许 margin:auto 工作的边距。