Search code examples
htmlcssflexboxvertical-alignment

HTML, CSS - Aligning Buttons To The Center Of Page


I want to align some buttons to the center of the page. May I please know how can I do it here in my CSS.

button {
  background-color: #6495ED;
  color: white;
  padding: 16px 25px;
  margin: 0 auto;
  border: none;
  cursor: pointer;
  width: 100%;
  border-radius: 8px;
  display: block;
  position: middle;
}
<button type="button" onclick="document.getElementById('id01').style.display='block'" style="width: auto;">User Login</button>
<br><br><br>
<button type="button" onclick="document.getElementById('id02').style.display='block'" style="width:auto; ">Admin Login</button>


Solution

  • If flexbox is an option, you can add this:

    body {
      margin: 0;
      height: 100vh; // stretch body to the whole page
      display: flex; // define a flex container
      flex-direction: column; // arrange items in column
      justify-content: center; // align vertically center
    }
    

    (Note that position: middle is invalid)

    See demo below:

    body {
      margin: 0;
      height: 100vh;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }
    
    button {
      background-color: #6495ED;
      color: white;
      padding: 16px 25px;
      margin: 0 auto;
      border: none;
      cursor: pointer;
      width: 100%;
      border-radius: 8px;
    }
    <button type="button" onclick="document.getElementById('id01').style.display='block'" style="width: auto;">User Login</button>
    <br><br><br>
    <button type="button" onclick="document.getElementById('id02').style.display='block'" style="width:auto; ">Admin Login</button>