gpt4 book ai didi

html - Flexbox 不垂直居中内容

转载 作者:搜寻专家 更新时间:2023-10-31 23:22:53 25 4
gpt4 key购买 nike

所以我尝试使用 flexbox 将我的名字放在屏幕中间。

在浏览了许多教程之后,他们说我完成此任务所需的唯一代码是...

div {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
<div>
<h1>
David
</h1>
</div>

jsFiddle

如果您尝试上面的代码,它只会使框水平居中。

我找到了一些其他的代码来达到预期的效果:

div {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
width: 100%;
position: absolute;
}
<div>
<h1>
David
</h1>
</div>

jsFiddle

但这似乎有点老套,而且似乎是错误的。

对于我做错的任何帮助,我将不胜感激。

谢谢。

最佳答案

在 CSS 中, block 级元素通常默认占据父元素的 100% 宽度

因此,无需执行任何操作,h1 将展开以覆盖其父级的整个宽度:

div { border: 1px solid black; }
h1 { background-color: yellow; }
<div>
<h1>
David
</h1>
</div>

但是,同样的行为适用于高度。您需要为容器指定高度,否则它默认为 height: auto(内容的高度)。

因此,内容水平居中而非垂直居中。

水平方向上,有足够的空间可以四处移动,居中也没有问题。

在垂直方向上,没有空间可以去,因为没有额外的高度。

Solution: Add height to your container.

html, body {
height: 100%;
margin: 0;
}

div {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100%;
}
<div>
<h1>
David
</h1>
</div>

Revised Fiddle

引用资料:

关于html - Flexbox 不垂直居中内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37223622/

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