Single CSS selector to match N elements when there are N elements

Viewed 87

This is similar to this question CSS select first child only if two children but more generic. I have specific task to select both children if there are 2 children.

I came up with this:

li:nth-child(1):nth-last-child(2), li:nth-child(2):nth-last-child(1)

it works, but I was wondering if it's possible to make it with single selector. If so, can this be generalized with pattern and make it work with any number of elements like 3 children if there are only 3 elements or all 4 children if there are only 4 children.

This is useful if you have delete button but you need minimal of N items and want to hide the button when there are min number of items.

1 Answers

I think the best you could do is:

.box > *:nth-last-child(3):first-child,
.box > *:nth-last-child(3):first-child ~ * {
  color: red;
}

/*
.box > *:nth-last-child(N):first-child,
.box > *:nth-last-child(N):first-child ~ * {
  color: red;
}
*/
<div class="box">
  <span>text</span>
</div>
<div class="box">
  <span>text</span>
  <span>text</span>
</div>
<div class="box">
  <span>text</span>
  <span>text</span>
  <span>text</span>
</div>
<div class="box">
  <span>text</span>
  <span>text</span>
  <span>text</span>
  <span>text</span>
</div>

Related