Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 685
David Avatar asked May 14 '16 06:05

David


People also ask

How do I align content vertically?

The CSS just sizes the div, vertically center aligns the span by setting the div's line-height equal to its height, and makes the span an inline-block with vertical-align: middle. Then it sets the line-height back to normal for the span, so its contents will flow naturally inside the block.


1 Answers

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
like image 125
Michael Benjamin Avatar answered Oct 27 '22 00:10

Michael Benjamin