0

Below is my CSS and HTML respectively:

body {
    display: flex;
    background-color: #333;
    height: 100%;
    margin: 0;
    padding: 0;
    align-items: center;
    justify-content: center;
}

div {
    width: 170px;
    height: 170px;
    background-color: #0073d9;
} 
<html>
<body>
   <div></div>
</body>
</html>

I know this is a simple question, but I just cannot fix it. I have put the align-items property and assigned "center" value to the body, I don't understand why the 170px by 170px square still can't be placed in center vertically.

I will be grateful if you can let me know where I get wrong. Thanks very much.

Joshua
  • 3,055
  • 3
  • 22
  • 37
Eric
  • 69
  • 7

1 Answers1

2

It is centered. Body just has the same height as the element. If you create higher body (for example 100vh which means 100% of viewport) you can see it is centered.

body {
    display: flex;
    background-color: #333;
    height: 100vh;
    margin: 0;
    padding: 0;
    align-items: center;
    justify-content: center;
}

div {
    width: 170px;
    height: 170px;
    background-color: #0073d9;
} 
<html>
<body>
   <div></div>
</body>
</html>
Jax-p
  • 7,225
  • 4
  • 28
  • 58
  • Thanks for your great help. Yes, I understand to most of people this is simple, but not me at this moment. Thanks. – Eric Nov 22 '21 at 08:34
  • Its ok. `height: 100%` can be tricky but it is 100% of the parent element and there is no parent element here. – Jax-p Nov 22 '21 at 08:35