我有一个宽度为 100% 的 div。
我想在其中居中放置一个按钮,我该怎么做?
<div style="width:100%; height:100%; border: 1px solid">
<button type="button">hello</button>
</div>
最佳答案
更新答案
更新是因为我注意到这是一个积极的答案,但是 Flexbox 现在是正确的方法。
Live Demo
垂直和水平对齐。
#wrapper {
display: flex;
align-items: center;
justify-content: center;
}
只是水平的(只要主 flex 轴是水平的,这是默认的)
#wrapper {
display: flex;
justify-content: center;
}
使用固定宽度且没有 flexbox 的原始答案
如果原始海报想要垂直和居中对齐,对于按钮的固定宽度和高度非常容易,请尝试以下操作
Live Demo
CSS
button{
height:20px;
width:100px;
margin: -20px -50px;
position:relative;
top:50%;
left:50%;
}
对于水平对齐,请使用任一
button{
margin: 0 auto;
}
或
div{
text-align:center;
}
https://stackoverflow.com/questions/7560832/