Search code examples
htmlcsscentervertical-alignment

How can I center a div which is direct child to body?


I'm trying to center this div both main axis and cross axis but justify-content works but align item doesn't. Can't figure out why it is happening.

* {
  margin: 0;
  padding: 0;
}

body {
  font-size: 10px;
  background-color: rgb(255, 255, 255);
  display: flex;
  flex-direction: column;
  align-items: center;
}
<div class="formdiv">
  <form class="form">

    <br>
    <label for="email">Username</label>
    <br>
    <input type="email" id="email" placeholder="Username" required>
    <br>
    <label for="password">Password</label>
    <br>
    <input type="text" id="password" placeholder="Password" required>
    <br>
    <button>submit</button>

  </form>
</div>


Solution

  • The div and the form are centered, but the body is only as tall as they are. You'd have to give it a larger height.

    body {
      min-height: 100vh;
    }
    
    body {
      font-size: 10px;
      background-color: rgb(255, 255, 255);
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
    <div class="formdiv">
      <form class="form">
    
        <br>
        <label for="email">Username</label>
        <br>
        <input type="email" id="email" placeholder="Username" required>
        <br>
        <label for="password">Password</label>
        <br>
        <input type="text" id="password" placeholder="Password" required>
        <br>
        <button>submit</button>
    
      </form>
    </div>