HTML,CSS - 将按钮对齐到页面中心

时间:2017-09-16 13:52:44

标签: html css css3 vertical-alignment

我想将按钮对齐到页面中心。我可以知道如何在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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:4)

如果flexbox是一个选项,您可以添加:

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
}

(请注意,position: middle 无效

见下面的演示:

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>

答案 1 :(得分:2)

如果您不想使用Flexbox,只需将button包裹在div中并将其position设置为absolute,{ {1}}到top50%left50%transform,也会给父母或translate(-50%, -50%)元素{{1 }} body

请注意,position或包含relative的父级必须定义为body

&#13;
&#13;
.buttons-holder
&#13;
height
&#13;
&#13;
&#13;