gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 11:27:35 25 4
gpt4 key购买 nike

如果我在具有 text-align: center 的父级中有一个 position: absolute 内联子级,结果就像我写了 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 定位在左边缘在父级的 50%,这意味着 div 更右对齐而不是居中。

奇怪的是 text-align: center 在父级上,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 的行为“符合预期”。

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

由于此行为在除 IE(包括 Microsoft Edge)之外的所有浏览器之间都是可互操作的,因此它很可能在 css-position(目前与 CSS2 做出相同假设)、css-text、css-display 中有特殊情况,或其组合,而不是被更正并可能破坏任何已经依赖它的网站。

关于css - text-align: center on absolutely-positioned child behaviors like left: 50%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43922199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com