我正在尝试使用CSS和jQuery的组合来水平居中一系列对象。 jQuery部分是我遇到的麻烦。这是我的代码:
$('.tooltip').each(function() {
$(this).css('margin-left', 0 - ($(this).width / 2) );
}
上面的代码应该应用一个负边距 - 左边正好是对象宽度的一半。我做错了什么?
答案 0 :(得分:2)
$('.tooltip').each(function() {
$(this).css('margin-left', '-'+($(this).width() / 2)+'px');
}
答案 1 :(得分:1)
.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');
}