Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can CSS detect the number of children an element has?

I'm probably answering my own question, but I'm extremely curious.

I know that CSS can select individual children of a parent, but is there support to style the children of a container, if its parent has a certain amount of children.

for example

container:children(8) {   // style the parent this way if there are 8 children } 

I know it sounds weird, but my manager asked me to check it out, haven't found anything on my own so I decided to turn to SO before ending the search.

like image 807
Brodie Avatar asked Jan 04 '12 01:01

Brodie


People also ask

Does CSS apply to child elements?

It's easy to apply style to a child element, but if you want to apply style to a parent class that already has child elements, you can use the CSS selector child combinators (>), which are placed between two CSS selectors. For example, div > p selects all <p> elements where the parent is a <div> element.

Can CSS be used to find child => parent page element?

There is currently no way to select the parent of an element in CSS, at least not a way that works across all browsers.

How do I find my child in CSS?

The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.


1 Answers

Clarification:

Because of a previous phrasing in the original question, a few SO citizens have raised concerns that this answer could be misleading. Note that, in CSS3, styles cannot be applied to a parent node based on the number of children it has. However, styles can be applied to the children nodes based on the number of siblings they have.


Original answer:

Incredibly, this is now possible purely in CSS3.

/* one item */ li:first-child:nth-last-child(1) { /* -or- li:only-child { */     width: 100%; }  /* two items */ li:first-child:nth-last-child(2), li:first-child:nth-last-child(2) ~ li {     width: 50%; }  /* three items */ li:first-child:nth-last-child(3), li:first-child:nth-last-child(3) ~ li {     width: 33.3333%; }  /* four items */ li:first-child:nth-last-child(4), li:first-child:nth-last-child(4) ~ li {     width: 25%; } 

The trick is to select the first child when it's also the nth-from-the-last child. This effectively selects based on the number of siblings.

Credit for this technique goes to André Luís (discovered) & Lea Verou (refined).

Don't you just love CSS3? 😄

CodePen Example:

  • https://codepen.io/mattlubner-the-decoder/pen/ExaQZQR

Sources:

  • http://andr3.net/blog/post/142 (André Luís)
  • http://lea.verou.me/2011/01/styling-children-based-on-their-number-with-css3/ (Lea Verou)
like image 120
Matthemattics Avatar answered Sep 25 '22 21:09

Matthemattics