我有一个div,宽度为100%。
我想在其中居中一个按钮,我该怎么做呢?
< div风格= "宽度:100%;高度:100%;边框:1px实心"> <按钮type = "按钮" >你好> < /按钮 < / div >
我有一个div,宽度为100%。
我想在其中居中一个按钮,我该怎么做呢?
< div风格= "宽度:100%;高度:100%;边框:1px实心"> <按钮type = "按钮" >你好> < /按钮 < / div >
当前回答
更新后的答案
更新是因为我注意到这是一个积极的答案,但现在Flexbox将是正确的方法。
现场演示
垂直和水平对齐。
#wrapper {
display: flex;
align-items: center;
justify-content: center;
}
只是水平(只要主伸缩轴是水平的,这是默认的)
#wrapper {
display: flex;
justify-content: center;
}
原来的答案使用固定宽度和不灵活
如果原来的海报想要垂直和中心对齐,它很容易固定宽度和高度的按钮,尝试以下
现场演示
CSS
button{
height:20px;
width:100px;
margin: -20px -50px;
position:relative;
top:50%;
left:50%;
}
对于水平对齐使用任何一种
button{
margin: 0 auto;
}
or
div{
text-align:center;
}
其他回答
你应该把它简单化:
首先你有你的文本或按钮的初始位置:
<div style="background-color:green; height:200px; width:400px; margin:0 0 0 35%;">
<h2> Simple Text </h2>
<div>
<button> Simple Button </button>
</div>
</div>
通过将此css代码行添加到h2标记或包含按钮标记的div标记
样式:" text-align:center; "
结果代码将是:
<div style="background-color:green; height:200px; width:400px; margin:0 0 0 35%;">
<h2 style="text-align:center;"> Simple Text </h2> <!-- <<--- here the changes -->
<div style="text-align:center"> <!-- <<--- here the changes -->
<button> Simple Button </button>
</div>
</div>
由于提供了有限的细节,我将假设最简单的情况,并说你可以使用text-align: center:
http://jsfiddle.net/pMxty/
假设div是#div, button是#button:
#div {
display: table-cell;
width: 100%;
height: 100%;
text-align: center;
vertical-align: center;
}
#button {}
然后像往常一样将按钮嵌套到div中。
最简单的方法是输入一个“div”,给它一个“margin:0 auto”,但如果你想让它居中,你需要给它一个宽度
Div{
Margin: 0 auto ;
Width: 100px ;
}
div { Text-align: center; } 按钮{ 宽度:50%; 保证金:1rem auto; } < div风格= "宽度:100%;高度:100%;边框:1px实心"> <按钮type = "按钮" >你好> < /按钮 < / div >
这是我经常做的事。 我认为bootstrap也在“mx-auto”中使用这个。