Javascript jQuery:水平居中绝对位置对象

Javascript jQuery:水平居中绝对位置对象,javascript,jquery,css,Javascript,Jquery,Css,我正在尝试使用CSS和jQuery的组合将一系列对象水平居中。jQuery部分是我遇到的问题。这是我的密码: $('.tooltip').each(function() { $(this).css('margin-left', 0 - ($(this).width / 2) ); } 上面的代码应该应用负的左边距,正好是对象宽度的一半。我做错了什么 .tooltip { position: absolute; width: 300px; // suppose

我正在尝试使用CSS和jQuery的组合将一系列对象水平居中。jQuery部分是我遇到的问题。这是我的密码:

$('.tooltip').each(function() {
        $(this).css('margin-left', 0 - ($(this).width / 2) );
}
上面的代码应该应用负的左边距,正好是对象宽度的一半。我做错了什么

.tooltip {
   position: absolute; 
   width: 300px; // suppose
   left: 50%;
   margin-left: -150px; // half of the width
}
使用jQuery:

$('.tooltip').each(function() {
        $(this).css('margin-left', '-' + $(this).width / 2 + 'px');
}
使用jQuery:

$('.tooltip').each(function() {
        $(this).css('margin-left', '-' + $(this).width / 2 + 'px');
}

去掉零,这是一个函数!哦,酷。看起来怎么样?去掉零,这是一个函数!哦,酷。看起来怎么样?@colindunnn让我们试试jquerysolution@colindunnn因此,让我们试试jquery解决方案