[英]Aligning a button center middle (long text)
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
width
是100px
,你需要否定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;
所以在你的情况下,我硬编码250px
的width
所以我否定-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 */
}
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;
}
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.