4

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?

Pierre P.
  • 1,055
  • 2
  • 14
  • 26

2 Answers2

5

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.

Johannes
  • 64,305
  • 18
  • 73
  • 130
2

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.

Drozerah
  • 236
  • 3
  • 9