Animate <pre> tag width to fit content on hover

<pre> tags are fab for showing code snippets nicely indented, but the resultant line length can end up wider than the available space of the page’s content area, leaving us with a nasty overlap, or having to resort to nasty horizontal scrollbars using overflow: auto. Wouldn’t it be nice if they could fit neatly within their containers, but expand to fit when hovered over?

Luckily, this is not too hard to do. In fact we can bash out a quick first pass using CSS:

pre { overflow: hidden; }
pre:hover { overflow: visible; }

This works fine (provided you’re not using ie6), but it’s rather an abrupt transition. A tiny smattering of jQuery and we can get it nicely smoothed out:

$(this).each(function() {

    var $p = $(this),
        w = $p.width(),

        // setting position to absolute means the element will only take up the width of its contents, and overflow to visible so we can capture this width
        w2 = $p.css({position: 'absolute', overflow: 'visible'}).width();

    // reset css
    $p.css({position: '', overflow: 'hidden'});

    if (w2 - w > 5) {

        $p.hover(function() {
            $p.stop().animate({width: w2 + 'px'});
        }, function() {
                $p.stop().animate({width: w + 'px'});
        });
    }
});

Unless you have text size set to very tiny in your browser, you should be able to see the effect when you hover over the code above.