Reputation: 525
I have created a simple jQuery & CSS based tooltip which is not aligned horizontally even though i made positioning relative for the parent anchor link element.
If i set the width of the tooltip to 100px or something else it works but the content may extend so I want to avoid defining the width.
HTML Code
<div class="single-session-speakers">
<div class="single_session_speaker_thumb iva_tip">
<a href="#"><img alt="Anne-Marie" src="http://placehold.it/50x50">
<span class="ttip">Anne-Marie</span></a>
</div>
<div class="single_session_speaker_thumb iva_tip">
<a href="#"><img alt="Kristin Ellison" src="http://placehold.it/50x50">
<span class="ttip">Kristin</span></a>
</div>
<div class="single_session_speaker_thumb iva_tip">
<a href="#"><img alt="John McWade" src="http://placehold.it/50x50">
<span class="ttip">John McWade</span></a>
</div>
<div class="single_session_speaker_thumb iva_tip">
<a href="#"><img alt="Chris Converse" src="http://placehold.it/50x50">
<span class="ttip">Chris Converse Mark</span></a>
</div>
</div>
jQuery Code
$('.iva_tip').hover(function () {
$(this).find('span.ttip').fadeIn();
}, function () {
$(this).find('span.ttip').fadeOut();
});
CSS Code
.single_session_speaker_thumb {
position: relative;
display: inline-block;
text-align: center;
margin: 0 4% 4% 0;
}
.single_session_speaker_thumb a { display: block;}
.ttip {
display: none;
position: absolute;
bottom: 115%;
left: -50%;
padding: 0.5em 1em;
font-size: 13px;
line-height: 15px;
margin-left: 6px;
white-space: nowrap;
background: #22222b;
color: #d1d1de;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.ttip::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -6px;
border-top-color: inherit;
border-top: 6px solid #333333;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
}
What I'm doing wrong? Please let me know. Here is the JSFiddle
Upvotes: 5
Views: 370
Reputation: 6467
As you said, tooltip's width depends on content. Then you will need to align it using JS
code instead of CSS
as follows:
// Getting position based on width of gray-box and tooltip
var left = (grayBoxWidth - tooltipWidth) / 2;
// Setting calculated left-position to tooltip element
$(this).find('span.ttip').css('left', left).fadeIn();
See this working JSFiddle
Upvotes: 3