开发者

Parent div float interferes the child div's width

What I am trying to do is to have a very simple tooltip that hides/shows on hover using jQuery.

(jsFiddle demo of the problem)

To do this, what I did was to put a di开发者_运维知识库v on li's that will have a tooltip. This div is absolutely positioned on top of each li. The tooltip div will contain varying lengths of text so I cannot just pre-define its width. I just want the width to extend all the way depending on the text length.

My problem is that when I float the li, the div also gets floated (or so it seems) hence taking the width of the floated li. The tooltip now becomes as narrow as the width of the li, which I don't like to happen.

This is the HTML:

<ul id="images">
    <li><img src="[some image]" /><div class="tooltip">Some text that is quite long.</div></li>
    <li><div class="tooltip">Some text that is quite small.</div><img src="[some image]" /></li>
    <li><img src="[some image]" /></li>
    <li><img src="[some image]" /></li>
</ul>

This is the CSS:

#images li {
    list-style: none;
    margin-left: 10px;
    position: relative;
}

.tooltip {
    color: #FFF;
    clear: both;
    background: #000;
    padding: 10px;
    font: 11px Arial, Helvetica, sans-serif; 
    -moz-border-radius: 5px;
    position: absolute;
    top: -50px;
    display: none;
    border: 2px solid #999;
}

I hope someone would help me with this problem.


You can always calculate the exact width before.

For example, you create a tooltip div outside of your page like

<div class="tooltip" id="calc"></div>

and

#calc{
  top:-100px;
  left:-100px;
}

If you add the following js, it will show nicely

$(".tooltip","#images").each(function(){
  $("#calc").text($(this).text());
  $(this).width($("#calc").width());
});

updated fiddle here


Block elements expand to the width of their containers. Float doesn't change this.

If you want a different width on the tool-top use width and specify the width in pixels.

If you want to go a fancier route, you can define a width and height, check for overflow and make it wider using JavaScript.


I think you need to change your approach a bit! Instead of using the same div as the actual tooltip, you can use its HTML content inside a div that has an absolute position and you set its position based on the position of the object being hovered.

$('#images li').hover(function() {
  $('#myTooltip').html($(this).find('.tooltip').html());
  /* Here you need to set #myTooltip absolute position. 
     based on the position of $('this') or the mouse position
     with an offset */

}, function() {
  $('#myTooltip').hide();
});

where #myTooltip is a div defined outside your list that has an absolute position.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜