text-align:以 absolutely-positioned 为中心 child 表现得像左边:50%

text-align: center on absolutely-positioned child behaves like left: 50%

如果我在带有 text-align: center 的 parent 中有一个 position: absolute 内联 child,结果就像我写 left: 50% 一样,而不是比实际居中 div.

当然这是一个不寻常的案例,因为这两者不能一起使用,我不会依赖它们进行生产,但我试图理解为什么会这样。

CodePen

.centered,
.positioned {
  border: 1px solid blue;
  margin-bottom: 20px;
  height: 200px;
  position: relative;
}

.centered {
  text-align: center;
}

.centered .child,
.positioned .child {
  width: 100px;
  height: 100px;
  border: 1px solid red;
  position: absolute;
  display: inline-block;
}

.positioned .child {
  left: 50%;
  transform: translate(-50%, 0);
}
<div class="centered">
  <div class="child"></div>
</div>

<div class="positioned">
  <div class="child"></div>
</div>

当您使用 left: 50% 时,您要么需要等于元素宽度一半的负值 margin-left,要么需要 -50% 的变换,因为 dom 正在定位parent 的 50% 的左边缘,意味着 div 更 right-aligned 而不是居中。

奇怪的是 parent 上的 text-align: center 和 child 上的 position: absolute 也表现得像这样。 text-align: center 不能考虑 child 的宽度吗?就算是专门设置的?

这是一个 known issue 似乎是故意的,至少在 Chrome:

The breakage was caused by http://wkrev.com/126911 which fixed an earlier issue, and according to the commit (and commits/bugs it references) this is the intentional behavior, making this an error on the website itself.

Talking to Robert Hogan, author of the patch, it's not entirely certain what should happen here, and I can't find where in CSS 2.1 this is defined. It boils down to whether absolutely positioned elements, which makes them block level per section 9.7 of CSS 2.1, should ever be laid out in a line. WebKit has quite some machinery for this, so the behavior definitely is deliberate.

Furthermore, Firefox matches what Chromium does here, and shows the same result on http://m.csl-sofas.co.uk. I can test Opera and IE tonight. As we match other browsers I'd be inclined to say that the website should fix it, but I don't yet know where in the specification this is defined.

While investigating this, John and I did find an interesting discrepancy in the computed style output, namely that while rendering of the block changed while flipping between display: block and inline-block, the computed style (rightfully) continued showing display: block, as is implied by position: absolute.

只有 IE 的行为“符合预期”。

我猜 CSS 中没有定义的原因很简单,因为 CSS 假设所有绝对定位的元素在确定布局时都被阻塞了,因为你永远无法有一个内联的绝对定位元素 — 任何绝对定位元素的显示计算值始终是其指定值的块级对应值。

由于此行为可在除 IE(包括 Microsoft Edge)之外的所有浏览器之间互操作,因此它很可能在 css 位置(目前与 CSS2)、css-文本、css-显示或它们的组合,而不是被更正并可能破坏任何已经依赖它的网站。