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

Time:08-14

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>

CodePudding user response:

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 >
  <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;
}

CodePudding user response:

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 >
  <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>

CodePudding user response:

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

  • Related