我有一个div,宽度为100%。
我想在其中居中一个按钮,我该怎么做呢?
< div风格= "宽度:100%;高度:100%;边框:1px实心"> <按钮type = "按钮" >你好> < /按钮 < / div >
我有一个div,宽度为100%。
我想在其中居中一个按钮,我该怎么做呢?
< div风格= "宽度:100%;高度:100%;边框:1px实心"> <按钮type = "按钮" >你好> < /按钮 < / div >
当前回答
var element = document.getElementById('btn1'); var elementwidth = element.clientWidth; var elementheight = element.clientHeight; Element.style.left = 'calc(50% - ('+elementwidth+'px / 2))'; Element.style.top = 'calc(50% - ('+elementheight+'px / 2))'; # btn1 { 位置:相对; } div { 身高:200 px; 宽度:200 px; 边框:1px纯黑色; } < html > <身体> < div > <input type = 'button' id = 'btn1'> < / div > 身体< / > < / html >
其他回答
使用flexbox
.Center {
display: flex;
align-items: center;
justify-content: center;
}
然后将类添加到按钮中。
<button class="Center">Demo</button>
div { Text-align: center; } 按钮{ 宽度:50%; 保证金:1rem auto; } < div风格= "宽度:100%;高度:100%;边框:1px实心"> <按钮type = "按钮" >你好> < /按钮 < / div >
这是我经常做的事。 我认为bootstrap也在“mx-auto”中使用这个。
要将<button type = "button">在<div>中垂直和水平居中,宽度是动态计算的,就像在你的例子中一样,下面是要做的:
设置文本对齐:居中;到换行<div>:当你调整<div>(或者窗口)的大小时,这将使按钮居中。 对于垂直对齐,你需要设置margin: valuepx;对于按钮。下面是计算valuepx的规则: valuepx = (wrappingDIVheight - buttonHeight)/2
这是一个JS Bin的演示。
最简单的方法是输入一个“div”,给它一个“margin:0 auto”,但如果你想让它居中,你需要给它一个宽度
Div{
Margin: 0 auto ;
Width: 100px ;
}
你应该把它简单化:
首先你有你的文本或按钮的初始位置:
<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>