简体   繁体   English

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

[英]Aligning a button center middle (long text)

I'm trying to align a button in the middle of a scalable/responsive div. 我正在尝试在可伸缩/响应div的中间对齐按钮。 The problem is, the button isn't actually centered here. 问题是,按钮实际上并不在这里居中。 What am I missing? 我错过了什么? fiddle 小提琴

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

When you use position: absolute; 当你使用position: absolute; for centering elements, you need to negate the margin which are half of the size of the absolute positioned element. 对于居中元素,您需要否定absolute定位元素大小一半的margin So say if your button is 100px in width you need to negate margin-left: -50px; 所以说如果你的button width100px ,你需要否定margin-left: -50px;

So in your case, am hardcoding 250px of the width so I negated -125px , same goes for height as well, if the height of the element is say 30px use margin-top: -15px; 所以在你的情况下,我硬编码250pxwidth所以我否定-125px ,同样适用于height ,如果元素的height30px使用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 演示


The other way to achieve this is to use display: table-cell; 实现这一目标的另一种方法是使用display: table-cell; with vertical-align set to middle vertical-align设置为middle


On the other hand, if you do not want to use negative margin you can use calc() as well 另一方面,如果您不想使用负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 演示2

Try this code: 试试这段代码:

DEMO DEMO

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

You have to reduce the height/ width of the button from it's position as well. 您还必须从其位置减小按钮的高度/宽度。 Try this 尝试这个

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

Fiddle DEMO 小提琴演示

Here is your updated fiddle http://jsfiddle.net/pMxty/122/ 这是你更新的小提琴http://jsfiddle.net/pMxty/122/

a Bit of jQuery resolves it. 一点jQuery解决了它。

HTML HTML

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

css CSS

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

jQuery 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();
});
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM