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!
Written by Elad Shechter
Related protips
6 Responses
Very nice and helpful trick.
This is clever but ugly. It isn't intuitive what elements the selector will affect.
In the future, :not(:first-child). But for supporting ie7 & ie8, this is one of the best solutions.
@tommy_pyatt: Seems intuitive to me. If this is not intuitive, is there any use of the adjacent selector that is?
@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.
Never thought of that, nice trick