Does jQuery tooltip not align horizontally?

I created a simple hint based on jQuery and CSS that is not horizontally aligned, although I did relative positioning for the anchor element of the parent element.

If I set the tooltip width to 100 pixels or something else, it works, but the content can expand, so I want to avoid determining 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 am I doing wrong? Please let me know. Here is the JSFiddle

+5
source share
2 answers

As you said, the width of the tooltip depends on the content. Then you 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 working JSFiddle

+3
source

This type of problem is always handled. What can I do to help, recommend this awasome Qtip2 plugin. This has many features, and you don’t need to worry about things like your problem. Take a look at the demos here.

0
source

Source: https://habr.com/ru/post/1241764/


All Articles