uugurw
Last Updated: February 25, 2016
·
29.36K
· elad2412
Elad1

CSS selector trick: select all elements except the first

Lots of time you need to create separators like when using breadcrumbs or between articles. This is a small trick I mostly use on list-items that will select all the elements except from the first.

Let's say, I have this HTML of breadcrumbs and I want to add separators between each li element.

<ul class="breadcrumbs">
        <li><a href="main.html">main</a></li>
        <li><a href="sport.html">sport</a></li>
        <li><a href="soccer.html">soccer</a></li>
</ul>

First i will reset the natural styles of list-items and then I will add the li elements 'float: left' to view them in a single row.

/*reset list style*/
ul,li{                  
list-style:none;
margin:0;
padding:0;
}
/*float list items left in one row */
li{
     float:left;
     padding:0 10px;
}

The trick is very easy, in CSS we have the sibling selector ("+"), if i will make selector that choose "li + li" it will select all list-items except the first .

/*select from the second item and up*/
.breadcrumbs li + li{border-left:solid 1px #ddd;}

That's all! I am using it all the time, for unwanted last/first separator.

LIVE EXAMPLE:
Link

  • Note: Works in all Browsers (Internet Explorer 7 And Above).

Enjoy!

6 Responses
Add your response

6496
55e7ce99e11493d90f3b61914500ea77

Very nice and helpful trick.

over 1 year ago ·
6593

This is clever but ugly. It isn't intuitive what elements the selector will affect.

over 1 year ago ·
6594
Elad1

In the future, :not(:first-child). But for supporting ie7 & ie8, this is one of the best solutions.

over 1 year ago ·
7046
02688ffd42b4265a4fa2ca1683115e4e

@tommy_pyatt: Seems intuitive to me. If this is not intuitive, is there any use of the adjacent selector that is?

over 1 year ago ·
7060

@thomshouse: It's unintuitive in that when you look at the selector it's not immediately apparent to another developer (or you in 6 months time) what it will affect. It's arguable that there isn't really a use of a selector that does this which is both inuitive and cross-browser compatible, but overriding the style with first:child would work ok as long as you're ok with the caveats when using that pseudo-selector with IE7 and 8.

Personally I'd try for a server-side addition of a 'first' class, and then override the style if I really needed to select all but the first element, but That's not a CSS-only solution. The method detailed here has merit! It is clever and it works, but I just don't think it's very elegant and could end up costing development time, especially if you're working as part of a team. Just a consideration.

over 1 year ago ·
9336
Black parker

Never thought of that, nice trick

over 1 year ago ·