Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flexbox center vertically and horizontally

Tags:

html

css

flexbox

I'd like to have a horizontally and vertically centered content on one of my webpage. I've done it like this.

<!DOCTYPE html>
<html>
  <head>
    <title>Eko</title>
    <%= csrf_meta_tags %>    
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>    
  </head>    
  <body>
    <div class="login-container">    
      <h1>Hello</h1>    
    </div>    
  <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </body>    
</html>

And this is my CSS.

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

However, the vertical center doesn't occur (just the horizontal). It works when I apply this CSS.

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

Why does it only work when we have it applied to body?

like image 900
Pierre P. Avatar asked Mar 09 '23 13:03

Pierre P.


2 Answers

Your container has no height settings, so it only uses as much vertical space as needed by its contents, therefore there will be no vertical centering. If you apply height: 100% to it (and also to body to have a reference height), it should work as desired.

like image 184
Johannes Avatar answered Mar 12 '23 02:03

Johannes


In addition you must give to both your html & body tags an height, for instance :

html, body{
    height: 100%;
}

So, your container is also vertically centered.

like image 22
Drozerah Avatar answered Mar 12 '23 04:03

Drozerah