6

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.

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
David
  • 63
  • 1
  • 1
  • 5

1 Answers1

8

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:

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701