Flexbox not centering content vertically

南楼画角 提交于 2019-12-10 15:34:25

问题


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.


回答1:


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:

  • How to Center Elements Vertically and Horizontally in Flexbox
  • Methods for Aligning Flex Items


来源:https://stackoverflow.com/questions/37223622/flexbox-not-centering-content-vertically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!