If I have the following markup:

<ul>
  <li>test1</li>
  <li>test2</li>
  <li>test3</li>
  <li>test4</li>
</ul>

I'm going to be displaying the list items horizontally and I'd like to add a margin between the elements, but I do not want any margins on the exterior of the list.

Essentially, I want a margin-right of 10px on all of the list elements except for the last one. I suppose I could identify the last element with a class or id and override the margin-right to 0, but that seems a little awkward to me. Any better suggestions out there?

Thanks!

5 answers

danwellman 5600
0
points
This was chosen as the best answer

Yes, I think your only truly cross-browser solution would be to use jQuery to remove the margin on the last item using the :last filter, something like:

$("#ul_id").children(":last").css("margin-right", 0);

but this will fail when JS is disabled on the client.

Personally, I see nothing wrong with adding a class name to the last element and overriding the margin in that way.

Answered almost 8 years ago by danwellman
  • hm.. adding jQuery just for this problem... if there is no other use for a javascript framework on that site, then i would recommend a solution with normal Javascript and CSS Sven Finke almost 8 years ago
  • of course. I tend to take it for granted that jQuery will be available as it usually is on most of my sites :D danwellman almost 8 years ago
2
points

There's a few ways to skin this cat.

If you want a pure CSS fix that'll work across most browsers (with the exception of IE6), you can use the first-child pseudo-selector, e.g.

ul li { margin-left: 10px; }
ul li:first-child { margin-left: 0; }

There's more info at quirksmode. There is also last-child, but as far as I can tell, no version of IE supports it yet.

If you absolutely must have IE6 support, using a class is going to be the easiest way.

Answered almost 8 years ago by Olly Hodgson
1
point

Hm... it depends on your customers if a pure CSS solution is the right thing for you :) But you could use this CSS code:

ul li{ margin-right:10px; }
ul li:last-child, li.last-child{ margin-right:0px; }

And in addition to this, if the user is running your site in IE6, you implement a little js code snippet to set a class to the list, the "last-child" class.

document.getElementById("yourListId").lastChild.className="last-child";

That should work fine :)

Answered almost 8 years ago by Sven Finke
  • Should work fine, except in my experience, IE6 trips over the pseudo selector, so you need a separate entry for each of the two selectors (i.e. li:last-child { stuff } li.last-child { stuff }) Olly Hodgson almost 8 years ago
0
points

So, jQuery solution is also awkward?

Answered almost 8 years ago by wasim shaikh
Andy Ford 533
0
points

untested, but have you tried putting a right margin on all LI's and an equal yet opposite negative margin on the UL?

ul { margin-right: -10px; }

ul li { margin-right: 10px; }
Answered almost 8 years ago by Andy Ford