Reputation: 3163
I'm trying to horizontally center a series of objects with a combination of CSS and jQuery. The jQuery part is what I'm having trouble with. Here is my code:
$('.tooltip').each(function() {
$(this).css('margin-left', 0 - ($(this).width / 2) );
}
The code above should apply a negative margin-left that is exactly half of the objects width. What am I doing wrong?
Upvotes: 0
Views: 95
Reputation: 318302
$('.tooltip').each(function() {
$(this).css('margin-left', '-'+($(this).width() / 2)+'px');
}
Upvotes: 2
Reputation: 87073
.tooltip {
position: absolute;
width: 300px; // suppose
left: 50%;
margin-left: -150px; // half of the width
}
Using jQuery:
$('.tooltip').each(function() {
$(this).css('margin-left', '-' + $(this).width / 2 + 'px');
}
Upvotes: 1