我有一个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 >
其他回答
由于提供了有限的细节,我将假设最简单的情况,并说你可以使用text-align: center:
http://jsfiddle.net/pMxty/
保证金:0自动;是水平定心的正确答案。 对于居中这两种方式,使用jquery:
var cenBtn = function() {
var W = $(window).width();
var H = $(window).height();
var BtnW = insert button width;
var BtnH = insert button height;
var LeftOff = (W / 2) - (BtnW / 2);
var TopOff = (H / 2) - (BtnH /2);
$("#buttonID").css({left: LeftOff, top: TopOff});
};
$(window).bind("load, resize", cenBtn);
更新……五年后,可以在父DIV元素上使用flexbox轻松地将按钮水平和垂直居中。
包括所有浏览器前缀,以获得最佳支持
div {
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-align : center;
-moz-box-align : center;
-ms-flex-align : center;
-webkit-align-items : center;
align-items : center ;
justify-content : center;
-webkit-justify-content : center;
-webkit-box-pack : center;
-moz-box-pack : center;
-ms-flex-pack : center;
}
#container { position: relative; margin: 20px; background: red; height: 300px; width: 400px; } #container div { display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; -webkit-box-align: center; -moz-box-align: center; -ms-flex-align: center; -webkit-align-items: center; align-items: center; justify-content: center; -webkit-box-pack: center; -moz-box-pack: center; -ms-flex-pack: center; -webkit-justify-content: center; justify-content: center; } <!-- using a container to make the 100% width and height mean something --> <div id="container"> <div style="width:100%; height:100%"> <button type="button">hello</button> </div> </div>
使用flexbox
.Center {
display: flex;
align-items: center;
justify-content: center;
}
然后将类添加到按钮中。
<button class="Center">Demo</button>
你应该把它简单化:
首先你有你的文本或按钮的初始位置:
<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>
想起来:
button {
width: 100px; // whatever your button's width
margin: 0 auto; // auto left/right margins
display: block;
}
更新:如果OP正在寻找水平和垂直中心,这个答案将做一个固定的宽度/高度元素。