Search code examples
htmlcsstooltip

How to make pure css floating tooltips (absolutely positioned span) dynamically resize to accommodate text


I recently had an idea for using the CSS pseudo-class :hover to display a styled tooltip when the mouse is hovered over a link.

The basic code for the link looks like this:

.hasTooltip {
    position:relative;
}
.hasTooltip span {
    display:none;
}

.hasTooltip:hover span {
    display:block;
    background-color:black;
    border-radius:5px;
    color:white;
    box-shadow:1px 1px 3px gray;
    position:absolute;
    padding:5px;
    top:1.3em;
    left:0px;   
    max-width:200px; /* I don't want the width to be too large... */
}
<a href="#" class="hasTooltip">This link has a tooltip!<span>This is the tooltip text!</span></a> 

The result is exactly what I want, but with one annoying problem: the span does not expand to accommodate text, and if I don't specify a width, the text is squashed.

I did some searching on Google, found a couple examples of work people had done (this example is creepily similar to what I've gotten), but no one seems to have addressed the span width problem I'm having.


Solution

  • I know this answer is extremely late, but it appears the key to your issue would be to use:

    white-space: nowrap;
    

    inside of your span, and get rid of any sort of width definition. Of course the drawback to this will be that the tooltip will only be able to support a single line. If you want a multiline solution you will most likely have to use javascript.

    Here is an example of of this method: http://jsbin.com/oxamez/1/edit

    An added bonus is that this works all the way down to IE7. If you do not need to support IE7, I would suggest folding the span, and img styles into a :before, and :after for the .tooltip. Then you can populate the text using the data-* attribute.