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)
.
This question is related to
css-selectors
css
Using nick craver's solution with selectivizr allows for a cross browser solution (IE6+)
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 ul except last li, use following code.
ul li:not(:last-child){ }
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;
}
}
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 */
},
},
};
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+).
.nav-menu li:not(:last-child){
// write some style here
}
this code should apply the style to all
How to select all children of an element except the last child using CSS?
Answer: this code will work
<style>
.parent *:not(:last-child) {
color:red;
}
</style>
<div class='parent'>
<p>this is paragraph</p>
<h1>this is heading</h1>
<b>text is bold</b>
</div>
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.
to find elements from last, use
<style>
ul li:nth-last-of-type(3n){ color:#a94442} /**/
</style>
Source: Stackoverflow.com