jQuery:水平居中绝对定位对象

jQuery: Horizontally center absolutely position objects

本文关键字:定位 对象 水平居中 jQuery      更新时间:2023-09-26

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

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

上面的代码应该应用一个负左边距,正好是对象宽度的一半。我做错了什么?

$('.tooltip').each(function() {
        $(this).css('margin-left', '-'+($(this).width() / 2)+'px');
}
.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');
}