Day 67: counting children

posted on

It’s time to get me up to speed with modern CSS. There’s so much new in CSS that I know too little about. To change that I’ve started #100DaysOfMoreOrLessModernCSS. Why more or less modern CSS? Because some topics will be about cutting-edge features, while other stuff has been around for quite a while already, but I just have little to no experience with it.


There are a lot of interesting things you can do with the :has() pseudo-class. I’ve already covered some of them on day 26.

If you want to style an element based on the number of direct children it has, you can do that with just CSS.
Let's say you want to style a list in a certain way when it contains at least three items. You use the :has() pseudo-class with the condition that it has a direct child item that is a third child.

Note: Firefox doesn't support :has() yet.

ul:has(>:nth-child(3)) {
border: 10px solid red;
}
  • A
  • B
  • A
  • B
  • C
  • A
  • B
  • C
  • D

If you want to limit the rule to only apply styles if the list contains exactly three items, you extend the condition and only select the <ul> if it contains a direct child item that is the third and last item.

ul:has(>:nth-child(3):last-child) {
border: 10px solid red;
}
  • A
  • B
  • A
  • B
  • C
  • A
  • B
  • C
  • D

See on CodePen.

Further reading