这个问题在这里已有答案:
我想将我的按钮对齐到页面的中心。我可以知道如何在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>
如果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>
如果你不想使用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>