Flexbox无法将内容垂直居中 [英] Flexbox not centering content vertically

查看:64
本文介绍了Flexbox无法将内容垂直居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图用flexbox在屏幕中间居中显示我的名字。



浏览了许多教程之后,他们说我唯一需要的代码要做到这一点,就是...



  div {display:flex; flex-direction:列;证明内容:中心; align-items:center;}  

 < div> < h1>大卫< / h1>< / div>  



jsFiddle



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



我发现了其他一些可以达到预期效果的代码:



  div {display:flex;证明内容:中心; align-items:居中;高度:100%;宽度:100%;位置:绝对;}  

 < div> < h1>大卫< / h1>< / div>  



jsFiddle



但它似乎有点黑,它似乎是错误的。



任何对我做错事的帮助都将受到赞赏。



谢谢。

解决方案

在CSS中,默认情况下,块级元素通常占据父级元素的 width 。 p>

因此,如果不执行任何操作, h1 将扩展为覆盖其父对象的整个宽度:



  div {边框:1像素纯黑色; } h1 {background-color:yellow; }  

 < div> < h1>大卫< / h1>< / div>  



相同的行为不适用于高度。您需要指定容器的高度,否则默认为 height:自动(内容的高度)。



因此,内容在水平方向居中,而不在垂直方向居中。



水平方向上,有足够的移动空间,并且没有居中问题。



垂直地,那里没有空间,因为没有多余的高度。


解决方案:为容器增加高度。


  html,正文{高度:100%; margin:0;} div {display:flex; flex-direction:列;证明内容:中心; align-items:居中;高度:100%;}  

 < div> < h1>大卫< / h1>< / div>  



修订的小提琴



参考:




So I am attempting to use flexbox to center my name in the middle of the screen.

After looking through many upon many tutorials they say the only code I need to accomplish this, is...

div {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

<div>
  <h1>
    David
  </h1>
</div>

jsFiddle

If you try the code above, it only centers the box horizontally.

I found some other code that accomplishes the desired effect:

div {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  position: absolute;
}

<div>
  <h1>
    David
  </h1>
</div>

jsFiddle

but it seems a little hacky, and it just seems wrong.

Any help in what I am doing wrong would definitely be much appreciated.

Thank You.

解决方案

In CSS, block-level elements normally take 100% width of the parent, by default.

So, without doing anything, an h1 will expand to cover the full width of its parent:

div { border: 1px solid black; }
h1  { background-color: yellow; }

<div>
  <h1>
    David
  </h1>
</div>

However, this same behavior does not apply to height. You need to specify height for a container or else it defaults to height: auto (height of the content).

For this reason, the content is centering horizontally but not vertically.

Horizontally, there is plenty of space to move around and there is no problem centering.

Vertically, there is no space to go because there is no extra height.

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

References:

这篇关于Flexbox无法将内容垂直居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆