CSS: Last element on line

benesch picture benesch · Mar 24, 2012 · Viewed 13.5k times · Source

I've got an unordered [inline] list of links that wraps across two lines:
links widget

<ul>
    <li><a href="http://google.com">Harvard Medical School</a></li>
    <li><a href="http://google.com">Harvard College</a></li>
    ...
</ul>

I add the dot separator via a CSS pseudo-element:

#widget-links li { display: inline; }
#widget-links li:after { content: " \00b7"; }

Unfortunately, the separator appears after the last element on each line. With just one line, I'd simply grab :last-child and remove the psuedo-element.

Any nifty tricks to hide that last dot with more than one line? I'm open to weird CSS, or JavaScript if absolutely necessary.

Answer

Jon picture Jon · Mar 24, 2012

Interesting question! Here's what I consider a "low-tech" solution with jQuery that does the trick:

$(function() {
    var lastElement = false;
    $("ul > li").each(function() {
        if (lastElement && lastElement.offset().top != $(this).offset().top) {
            lastElement.addClass("nobullet");
        }
        lastElement = $(this);
    }).last().addClass("nobullet");
});​

The algorithm is not hard to follow, but here's the idea: iterate over the elements, taking advantage that they all have the same properties (size, margin, display inline etc) that affect their position when the browser computes layout. Compare the vertical offset of each item with that of the previous one; if they differ, the previous one must have been at the end of the line so mark it for special treatment. Finally, mark the very last item in the set for special treatment as well, since by definition it is the last item in the line on which it appears.

IMHO the fact that this is a Javascript-based solution (can it be done without, I wonder?) is no problem at all here, as even if the script does not run there is only going to be an extremely slight visual degradation of your webpage.

See it in action.