Trying to center an absolutely positioned object horizontally using CSS and jQuery is proving to be a challenge. The use of jQuery is necessary due to the varying widths of the objects. Hover over the icons in my jsFiddle to see the issue.
Currently, I have applied a left: 50%
property, but I need to implement a negative margin-left
that is half of the object's width. Here is the code snippet where I am facing issues:
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>