Reputation: 3163
I'm trying to horizontally center an absolute positioned object with CSS and jQuery. The jQuery is necessary because the objects have varying widths. Mouse over the icons in my jsFiddle to see what I mean.
Right now I have a left: 50%
property applied, but I need to do a negative margin-left
that is half of the object's width. This is my code, not sure why it's not working:
jQuery
$('.tooltip').each(function() {
$(this).css('margin-left', '-'+($(this).width() / 2)+'px');
}
CSS
.toolbar .tooltip {
position: absolute;
left: 50%;
margin-top: 8px;
padding: 3px 8px;
display: none;
}
.toolbar li:hover .tooltip {
display: block;
}
HTML
<ul class="toolbar">
<li><img alt="Undo" src="undo.gif" /><span class="tooltip">Undo</span></li>
<li><img alt="Redo" src="redo.gif" /><span class="tooltip">Redo</span></li>
<li><img alt="Help" src="help.gif" /><span class="tooltip">Help</span></li>
<li><img alt="Feedback" src="feedback.gif" /><span class="tooltip">Feedback</span</li>
</ul>
Upvotes: 0
Views: 152
Reputation: 6779
Based on the block's width, I set left
accordingly.
$('.tooltip').each(function() {
// Assuming button block width is 32px.
$(this).css('left', (32 - ($(this).width())) / 2+'px');
});
Upvotes: 1
Reputation: 15550
Unclosed code mistake, updated code here
By the way, it has padding so you should use "outerWidth" instead of "width".You can corrected code here
Upvotes: 4