blacknighttext
blacknighttext

Reputation: 11

How to select second row from bottom with :nth-last-child?

I have 6 rows and I need to select 2 rows from bottom like this

<div>row1 - not selected</div>
<div>row2 - not selected</div>
<div>row3 - not selected</div>
<div>row4 - selected</div>
<div>row5 - selected</div>
<div>row6 - not selected</div>

Upvotes: 0

Views: 144

Answers (3)

JustAG33K
JustAG33K

Reputation: 1556

You will have to use the :nth-last-child(2n+0). This will select the last child from the bottom. Hope this helps.

For more information on :nth-last-child() see: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child

Upvotes: 0

Kamil Guliyev
Kamil Guliyev

Reputation: 177

The :nth-child() or :nth-last-child() CSS pseudo-class matches elements based on their position among a group of siblings. And :nth-last-child() counting from the end. So, dynamic code:

.parent div:nth-last-child(2),
.parent div:nth-last-child(3) {
  background-color: black;
  color: white;
}
<div class="parent">
  <div>row1 - not selected</div>
  <div>row2 - not selected</div>
  <div>row3 - not selected</div>
  <div>row4 - selected</div>
  <div>row5 - selected</div>
  <div>row6 - not selected</div>
</div>

Upvotes: 0

Astw41
Astw41

Reputation: 392

Nth-last-child needs a parent to work properly. It selects its child's position. If you have a list of divs (like in your example) and after that something else it won't work.

// HTML
<div class="a">
  <div>row1 - not selected</div>
  <div>row2 - not selected</div>
  <div>row3 - not selected</div>
  <div>row4 - selected</div>
  <div>row5 - selected</div>
  <div>row6 - not selected</div>
</div>
// CSS
.a div:nth-last-child(2), .a div:nth-last-child(3){
  background-color:red;
}

Upvotes: 1

Related Questions