Search code examples
htmlcsstooltip

Vertical scrollbar inside a div without overflow-y: scroll


I am trying to create a simular "tooltip" for my project.

enter image description here

The problem is that the parent container has the "overflow-y: scroll" property applied to it (I need a vertical scroll bar there) and it simply clips its children elements when I try to move them out of the container. Is there any way I can have a vertical scrollbar without overflow-y?

This is what I have and what I want to achieve:

enter image description here


Solution

  • Overflow does indeed eat up any elements you want to hang out of the side. That's what overflow does. For this exact reason, the tooltips tend to not be child elements of the element they relate to, but rather top-level elements positioned absolutely, figured out with JS.

    Essentially, you'd do something the likes of this:

    HTML

    <div id="tooltip"></div>
    <ul>
        <li>
            <a href="#">Todd</a>
            <div class="tooltip-content">Todd is a guy and he's pretty cool.</div>
        </li>
    </ul>
    

    The basic idea is to have a hidden div that contains your tooltip data, and another div in the top level which you position absolutely.

    JavaScript

        $("ul li a").hover(function(){
            //hover in
            $("#tooltip").html($(this).next().html()).show(); // put the content of .tooltip-content into #tooltip, and show it
            // figure out the position of the element we hovered over
            var tt_top = $(this).offset().top,
                tt_left = $(this).offset().left;
            // position the tooltip based on that data
            // same height, left + width of the ul, so the tooltip is on the right side of the ul
            $("#tooltip").css({
                top: tt_top
                left: tt_left + $("ul").width();
            });
        }, function(){
            // hover out
            $("#tooltip").empty().hide(); // empty and hide tooltip
        });
    

    For brevity, I've used jQuery here, but the same principles apply to a pure JavaScript solution as well, if you have the time for that.

    CSS

        #tooltip {
            position: absolute;
            display: none;
            /* tooltip styles */
        }
    
        .tooltip-content {
            display: none;
        }
    

    The tooltip container needs to be positioned absolutely. The top and left values are created in JavaScript. Add display:none; so it doesn't disrupt the rest of your page when unneeded.

    Also add display:none; to hide the .tooltip-content elements so that they are never visible; they're only containers for the HTML you want in the tooltip.

    I've not tested this code, but this is the basic principle of all tooltips, when you want to combat overflow.