Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to vertically align div on page with flexbox [duplicate]

Tags:

The following is not vertically aligning the div with text in browser tab (it is horizontally aligning correctly):

<div style="height: 100%; display: flex; align-items: center; justify-content: center;">

  <div>
    Some vertical and horizontal aligned text
  </div>

</div>

What is wrong?

like image 740
EricC Avatar asked Sep 26 '16 08:09

EricC


People also ask

How do I vertically align a div in Flex?

To vertically center our div we can add a single CSS property. By using align-items: center we can vertically center all flex items to the parent container along the cross axis of the flex container. The nice aspect of flexbox is the styles apply to all children of our flex container.

Does vertical align work with Flex?

With Flexbox, you can stop worrying. You can align anything (vertically or horizontally) quite painlessly with the align-items , align-self , and justify-content properties.

Which flexbox property helps align items vertically?

align-items and justify-content are the important properties to absolutely center text horizontally and vertically. Horizontally centering is managed by the justify-content property and vertical centering by align-items. Not only can align-items be used to center text it vertically centers any child element.

Which CSS property can be used to vertically align the flex boxes in the center of its container?

To center our box we use the align-items property to align our item on the cross axis, which in this case is the block axis running vertically. We use justify-content to align the item on the main axis, which in this case is the inline axis running horizontally.


2 Answers

The problem is with the height you given to the parent container. The height :100% does not take whole height. change that to 100vh or like that

Here is the updated Demo

.container{
  height: 100vh; 
  display: flex; 
  align-items: center; 
  justify-content: center;
}
<div class="container">
  <div>
    Some vertical and horizontal aligned text
  </div>
</div>
like image 135
Syam Pillai Avatar answered Sep 23 '22 22:09

Syam Pillai


Please try bellow following code

body, html{
  height:100%;
  width:100%;
  padding:0px;
  margin:0px;
}

.demo-wp{
  height: 100%; 
  display: flex; 
  align-items: center; 
  justify-content: center;
  background:green;
  height:100%;
}

.inner-div{
  background:gold;
  padding:20px;
}
<div class="demo-wp">

  <div class="inner-div">
    Some vertical and horizontal aligned text
  </div>

</div>
like image 35
Santosh Khalse Avatar answered Sep 22 '22 22:09

Santosh Khalse