对齐按钮中间中间(长文本)

时间:2014-02-05 11:41:50

标签: html css

我正在尝试在可伸缩/响应div的中间对齐按钮。问题是,按钮实际上并不在这里居中。我错过了什么? fiddle

div{
     text-align: center;  
}
button{
    position: absolute;
    top: 50%;
    left: 40%;
}

4 个答案:

答案 0 :(得分:2)

当您使用position: absolute;作为居中元素时,您需要否定margin,它是absolute定位元素大小的一半。如果您button 100px width margin-left: -50px;,则需要否定250px

因此,在您的情况下,我对width的{​​{1}}进行了硬编码,因此我否定了-125px,同样适用于height,如果height该元素是30px使用margin-top: -15px;

button{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -125px;
    width: 250px;

    /* Use height as well if you need so, along with margin-top which 
       will have 1/2 of the negative value of the elements height  */
}

Demo


实现此目的的另一种方法是使用display: table-cell;并将vertical-align设置为middle


另一方面,如果您不想使用否定margin,也可以使用calc()

button{
    position: absolute;
    top: 50%; /* Use calc here too if you define height */
    left: calc(50% - 125px); /* Half of the elements width */
    width: 250px;
}

Demo 2

答案 1 :(得分:1)

试试这段代码:

<强> DEMO

button{
    position: absolute;
    top: 50%;
    left:25%;
    width:50%
}

答案 2 :(得分:0)

您还必须从按钮的位置减小按钮的高度/宽度。 试试这个

button{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -112px;
    margin-top: -25px;
}

小提琴 DEMO

答案 3 :(得分:0)

这是您更新的小提琴http://jsfiddle.net/pMxty/122/

一些jQuery解决了它。

HTML

<div>
    <button>Load my random useless data</button>
</div>

CSS

div {
    text-align: center;
}
button {
    position: absolute;
    top: 50%;
}

的jQuery

function place()
{
    var a = $("div").outerWidth() / 2,
    b = $("button").outerWidth() / 2;
$("button").css({
    "left": (a - b)
});
}

$(document).ready(function(){
place();
$(window).resize(function(){
place();
});
});