gpt4 book ai didi

html - Flexbox align-items : baseline works, 但 align-self : baseline doesn't. 为什么?

转载 作者:太空狗 更新时间:2023-10-29 13:14:42 25 4
gpt4 key购买 nike

我似乎在观察 flexbox 的一些令人困惑的行为,特别是在尝试使用 align-self: baseline 时。基本问题是它根本行不通;以下片段演示了该问题:

.flex-form {
display: flex;
}

.flex-form label {
align-self: baseline;
}

input[type=text] {
border: 1px solid black;
font-size: 16px;
margin: 0 10px;
padding: 5px;
}

button {
background-color: white;
border: 1px solid black;
margin: 0;
}
<form class="flex-form">
<label>Label: </label>
<input type="text" placeholder=" " />
<button type="submit">Submit</button>
</form>

这是输出的截图:

如您所见,标签的基线与其他表单元素对齐,尽管设置了align-self: baseline。但是,如果我在父容器上使用 align-items: baseline,我会得到不同的结果:

.flex-form {
display: flex;
align-items: baseline;
}

input[type=text] {
border: 1px solid black;
font-size: 16px;
margin: 0 10px;
padding: 5px;
}

button {
align-self: stretch;
background-color: white;
border: 1px solid black;
margin: 0;
}
<form class="flex-form">
<label>Label: </label>
<input type="text" placeholder=" " />
<button type="submit">Submit</button>
</form>

根据规范,这是正确的行为,还是一个错误?如果是这样,为什么?有解决方法吗?作为引用,我在 macOS 10.11.6 上的 Chrome 54、Safari 9.1.2 和 Firefox 50 上进行了测试,它们似乎都显示出相同的结果。

最佳答案

解决方案

如果您想要所有元素的基线对齐,请应用 align-self: baseline到每个,或者更简单地说,设置 align-items: baseline在容器上。

解释

flex 容器的初始设置是 align-items: stretch .

这意味着所有 flex 元素都会扩展容器的整个横轴长度。

这就是您的布局中发生的事情。 EXCEPT,您已覆盖 align-items: stretch在一个 flex 元素( label )上,通过应用 align-self: baseline .

当其他 flex 元素拉伸(stretch)时,标签有一个 baseline说明——但没有引用点。

来自规范:

8.3. Cross-axis Alignment: the align-items and align-self properties

baseline

If the flex item’s inline axis is the same as the cross axis, this value is identical to flex-start.

Otherwise, it participates in baseline alignment: all participating flex items on the line are aligned such that their baselines align, and the item with the largest distance between its baseline and its cross-start margin edge is placed flush against the cross-start edge of the line.

好吧,让我们分解一下:

  • 第一行不适用。在这种情况下, flex 元素的内联轴与主轴(水平)相同,而不是交叉轴(垂直),所以baseline没有解析为 flex-start .

  • “...该行中所有参与的 flex 元素都对齐,以便它们的基线对齐...” 好吧,只有一个元素具有基线对齐。没有其他基准可供引用。显然,浏览器回退到 flex-start在这种情况下(但我还没有看到这种行为的官方引用)。

规范语言的其余部分与这个问题无关,但在这篇相关文章中有详细介绍: What's the difference between flex-start and baseline?

关于html - Flexbox align-items : baseline works, 但 align-self : baseline doesn't. 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40727657/

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