gpt4 book ai didi

html - 为什么 justify-content 不使我的 div 居中?

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

我试图将两个 div 水平居中放置在 daddy div 中。

Daddy div 设置为 flex-direction: column 因为我希望子 div 一个在另一个下面,但在页面的中心。

justify-content: center; 应该这样做但不起作用。

我终于让它与 align-self 一起工作,但是有什么解释为什么这么多代码不足以让 div 居中?

这是我的代码:

<div class="main">
<div class="child-1">HI</div>
<div class="child-2">WE BUILD AWESOME STUFF</div>
</div>

.main {
display: flex;
flex-direction: column;
justify-content: center;
}

最佳答案

主轴与横轴

考虑 flex 容器的主轴横轴:

enter image description here来源:W3C

在上图中,主轴是水平的,横轴是垂直的。这些是 flex 容器的默认方向。

但是,可以使用 flex-direction 轻松切换这些方向属性(property)。

/* main axis is horizontal, cross axis is vertical */
flex-direction: row;
flex-direction: row-reverse;

/* main axis is vertical, cross axis is horizontal */
flex-direction: column;
flex-direction: column-reverse;

(横轴始终垂直于主轴。)


justify-content 属性(仅适用于主轴)

justify-content 属性沿 flex 容器的主轴对齐 flex 元素。

换句话说,当您的容器是 flex-direction: row 时,这会使主轴水平。 justify-content: center 将按您的预期工作。

但是您已经将容器设置为 flex-direction: column。这意味着主轴现在是垂直的,justify-content 会将 flex 元素向上/向下定位,而不是向左/向右。

由于您的示例中没有额外的高度,因此您不会注意到任何不同; justify-content 没有工作空间。 (与 block 元素默认填充 100% 的宽度不同,必须定义高度。否则,元素默认为 auto——内容的高度。)但是给容器一些高度,看看会发生什么。


align-* 属性(仅适用于横轴)

align-selfalign-itemsalign-content 属性在 flex 容器的横轴上运行(同样,始终垂直于主轴)。

因为您的主轴是垂直的,align-* 属性将左/右对齐 flex 元素。这就是 align-self 使您的 div 居中的原因。


Quick Summary: Depending on the flex-direction, the main axis and cross axis switch, taking their assigned properties with them.


解决方案

如果您的目标是最少的代码,这就是您所需要的:

.main {
display: flex;
flex-direction: column;
align-items: center;
}

更多详情:In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

关于html - 为什么 justify-content 不使我的 div 居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35106814/

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