Reputation: 14016
How would I select all but the last child using CSS3 selectors?
For example, to get only the last child would be div:nth-last-child(1)
.
Upvotes: 594
Views: 405190
Reputation: 255
There is a :not
selector in css3. Use :not()
with :last-child
inside to select all children except last one. For example, to select all li
in ol
except last li
, use following code.
ol li:not(:last-child) {
color: red
}
<ol>
<li>
foo
</li>
<li>
foo
</li>
<li>
foo
</li>
</ol>
Upvotes: 23
Reputation: 11067
You can apply your style to all the div and re-initialize the last one with :last-child:
for example in CSS:
.yourclass{
border: 1px solid blue;
}
.yourclass:last-child{
border: 0;
}
or in SCSS:
.yourclass{
border: 1px solid rgba(255, 255, 255, 1);
&:last-child{
border: 0;
}
}
Edit: I wrote this at a time :not
was not covered by all browsers. Today I would be more balanced and would use this solution in some situations, for instance if you want to override a default behaviour.
Upvotes: 137
Reputation: 556
to find elements from last, use
<style>
ul li:not(:last-child){ color:#a94442}
</style>
Upvotes: 6
Reputation: 1275
Using a more generic selector, you can achieve this as seen below
& > *:not(:last-child) {/* styles here */}
Example
<div class="parent">
<div>Child one</div>
<div>Child two</div>
</div>
This will capture all the child DIV in the parent
Upvotes: 4
Reputation: 169
If you're using it within the nesting of the parent then the easiest way is:
&:not(:last-child){
....
}
Example:
.row { //parent
...
...
...
&:not(:last-child){
....
}
}
Upvotes: 9
Reputation: 322
.nav-menu li:not(:last-child){
// write some style here
}
this code should apply the style to all
Upvotes: 2
Reputation: 414
Nick Craver's solution gave me what I needed but to make it explicit for those using CSS-in-JS:
const styles = {
yourClass: {
/* Styles for all elements with this class */
'&:not(:last-child)': {
/* Styles for all EXCEPT the last element with this class */
},
},
};
Upvotes: 2
Reputation: 680
Nick Craver's solution works but you can also use this:
:nth-last-child(n+2) { /* Your code here */ }
Chris Coyier of CSS Tricks made a nice :nth tester for this.
Upvotes: 53
Reputation: 630339
You can use the negation pseudo-class :not()
against the :last-child
pseudo-class. Being introduced CSS Selectors Level 3, it doesn't work in IE8 or below:
:not(:last-child) { /* styles */ }
Upvotes: 1064
Reputation: 11115
Using nick craver's solution with selectivizr allows for a cross browser solution (IE6+)
Upvotes: 10
Reputation: 9685
When IE9 comes, it will be easier. A lot of the time though, you can switch the problem to one requiring :first-child and style the opposite side of the element (IE7+).
Upvotes: 20