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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With