简体   繁体   中英

jQuery tooltip not horizontally aligned?

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

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

This kind of issues is allways dificult to handle . What i could do to help is recomend this awasome plugin Qtip2 . This have a lot of features and you dont need to worry about with things like your problem now. Have a look in to the demos here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM