HTML,CSS - 将按钮对齐到页面中心[重复]

问题描述 投票:1回答:2

这个问题在这里已有答案:

我想将我的按钮对齐到页面的中心。我可以知道如何在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>
html css css3 vertical-alignment
2个回答
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>

2
投票

如果你不想使用Flexbox,只需将你的button包裹在div中,然后将它的position设置为absolute,将top设置为50%,将left设置为50%,将transform设置为translate(-50%, -50%),也可以将父级或body元素设置为position relative

请注意,包含body.buttons-holder或父级必须是定义的height

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
}

body {
  position: relative;
}

.buttons-holder {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

button {
  background: #6495ED;
  color: white;
  padding: 16px 25px;
  margin: 15px auto;
  border: none;
  cursor: pointer;
  width: 100%;
  border-radius: 8px;
  display: block;
}
<div class="buttons-holder">
  <button type="button" onclick="document.getElementById('id01').style.display='block'" style="width:auto">User Login</button>
  <button type="button" onclick="document.getElementById('id02').style.display='block'" style="width:auto">Admin Login</button>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.