Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Last element on line

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.

like image 861
benesch Avatar asked Mar 23 '12 23:03

benesch


People also ask

How do you target the last element in CSS?

The :last-child selector allows you to target the last element directly inside its containing element. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.

How do you select the last line in CSS?

The text-align-last property in CSS is used to set the last line of the paragraph just before the line break. The line break may be due to the natural ending of a paragraph, or it may be due to the use of <br> tag.

How do you not get the last element in CSS?

The :not() selector excludes the element passed to it from selection. The :last-child selector selects the last child. Combining these two above selector to excludes the last children (inner-div) of every parent div from the selection.


1 Answers

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.

like image 181
Jon Avatar answered Oct 04 '22 14:10

Jon