Selecting the last element among various nested containers

后端 未结 1 1770
一向
一向 2020-11-30 14:58

How can I select the last and deepest element in CSS?

Is there a way to improve this css code?

What solution do you proposed for a deep tree? (~15-25).

相关标签:
1条回答
  • 2020-11-30 15:58

    If I understand your question correctly, you want to target the last li tag in multiple uls, where the number of nesting levels in the uls is unpredictable.

    You want a selector that targets the "last and deepest element" in a containing block where the number of elements preceding it in the block are unknown and irrelevant.

    This doesn't appear to be possible with Selectors 2.1 or Selectors 3.

    The :last-child, :last-of-type and nth-child pseudo-classes work when the nesting levels are fixed. In a dynamic environment where there are multiple lists of varying nesting levels these selector rules will break.

    This will select the last li in the first level ul:

    div.case > ul > li:last-child
    

    This will select the last li in the second level ul:

    div.case > ul > li:last-child > ul > li:last-child
    

    This will select the last li in the third level ul:

    div.case > ul > li:last-child > ul > li:last-child > ul > li:last-child
    

    and so on...

    A solution, however, may exist in Selectors 4, which browsers haven't yet implemented:

    li:last-child:not(:has(> li))
    

    This rule targets last child lis that have no descendant lis, which matches your requirement.

    For now, however, if you know the nesting level for each of your ul containers you can apply a class to each targeted li.

    Thanks @BoltClock for help crafting the Selectors 4 rule (see comments).

    0 讨论(0)
提交回复
热议问题