David David - 6 months ago 12
HTML Question

Flexbox not centering content vertically

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...

.container {
display: flex;
justify-content: center;
align-items: center;
}


EXAMPLE

If you try this, it only centers the box horizontally. I found some other code that accomplishes the desired effect:

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


EXAMPLE

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.

Answer

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, your content is centering horizontally but not vertically. Horizontally, there is plenty of space to move around; there is no problem centering. But vertically, there is no space to go because there is no added height.

Hence, add height to your container. (Your solution is not as hacky as you might think.)

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:

Comments