gpt4 book ai didi

css - 当 flex 元素是独生子时居中

转载 作者:技术小花猫 更新时间:2023-10-29 11:17:27 24 4
gpt4 key购买 nike

我有一个可以包含一个或多个元素的 flex 容器。

如果有多个元素,我想使用空格来证明内容的合理性

justify-content: space-between;

如果只有一个元素,我希望它居中。

示例 codepen

仅使用 CSS 是否可行?

最佳答案

是的。 flexbox 规范使这成为可能。

.flex {
display: flex;
margin: 1em 0;
padding: 1em;
border: 1px solid red;
justify-content: space-between;
}

a:only-child {
margin: 0 auto;
}
<div class="flex">
<a>item 1</a>
<a>item 2</a>
</div>
<div class="flex">
<a>item 1</a>
</div>

来自规范:

8.1. Aligning with auto margins

Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

因此,基本上,在父级上使用 justify-content 并在子级上使用自动边距。

根据上述规则,当 only-child 选择器应用时,自动边距优先。

关于css - 当 flex 元素是独生子时居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45730120/

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