Home > database >  How do I choose the last item in nested div with css?
How do I choose the last item in nested div with css?

Time:03-15

I need to select the last div (only Subtask3 not task1 and task2) from the nested divs without adding class/id.

  <div>
      <div>Subtask1
       <div>Task1</div>
       <div>Task2</div>
       <div>Task3</div>
      </div>
    
      <div>Subtask2
        <div>Task1</div>
        <div>Task2</div>
        <div>Task3</div>
      </div>
    
      <div>Subtask3
        <div>Task1</div>
        <div>Task2</div>
      </div>
  </div>

I tried div>div:nth-last-of-type(-n 1) { color: green;} and div>div:last-child { color: green;} but it takes last Tasks as well (I need only the last Subtask ... in this case Subtask3) ... it shouldn't be static the third! because Subtasks could be more than 3. Any idea?

CodePudding user response:

Better to add class but you can use it :

div>div:not(div>div>div):last-child { 
  color: green;
}
div>div>div{
  color:black;
}

See JsFiddle here: https://jsfiddle.net/24kmd0t8/1/

CodePudding user response:

Try this. I hope I have helped you.

div:nth-last-child(-n 1){
  background: red;
} 
div>div>div:nth-child(n)
{
  background: white;
}
<div>
      <div>Subtask1
       <div>Task1</div>
       <div>Task2</div>
       <div>Task3</div>
      </div>
    
      <div>Subtask2
        <div>Task1</div>
        <div>Task2</div>
        <div>Task3</div>
      </div>
    
      <div>Subtask3
        <div>Task1</div>
        <div>Task2</div>
      </div>
  </div>

CodePudding user response:

I understand that you want to do it with CSS.

Anyway, I can give you a solution with JQUERY

 $('div').parent().closest('div').last().addClass("last");

  $('div').parent().closest('div').last().addClass("last");
.last {
  background: blue;
 }
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
      <div>Subtask1
       <div>Task1</div>
       <div>Task2</div>
       <div>Task3</div>
      </div>
    
      <div>Subtask2
        <div>Task1</div>
        <div>Task2</div>
        <div>Task3</div>
      </div>
    
      <div>Subtask3
        <div>Task1</div>
        <div>Task2</div>
      </div>
  </div>

  •  Tags:  
  • css
  • Related