Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Middle Child Pseudo-Class

Is there a way to use CSS selectors to get the middle child in a list of elements?

I know that there is no literal :middle-child selector, but is there another way without resorting to Javascript?

like image 269
Jason Avatar asked Jun 24 '13 03:06

Jason


People also ask

How do I select the middle 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.

What is a pseudo only child?

Pseudo-class :only-child The :only-child pseudo-class represents an element that has a parent element and whose parent element has no other element children.

What is the difference between the nth child () and Nth-of-type () selectors?

As a general rule, if you want to select an interval of a selector regardless of the type of element it is, use nth-child . However, if you want to select a specific type only and apply an interval selection from there, use nth-of-type .


2 Answers

This has been working well for me:

*:not(:first-child):not(:last-child) {
    ...
}

You can see an example of this here: http://codepen.io/bentomas/pen/Gwqoe

The one caveat to this is that it only works in IE 9+: http://caniuse.com/#feat=css-sel3

like image 130
bentomas Avatar answered Sep 21 '22 07:09

bentomas


While not elegant, if you know the upper and lower limits of the total number of elements, you could take a brute force approach to select the middle element.

For example, the following rules will select the middle element in a set of 5, 7, or 9 elements.

div:nth-child(3):nth-last-child(3) {
  /* The middle element in a set of 5 is the 3rd element */
}

div:nth-child(4):nth-last-child(4) {
  /* The middle element in a set of 7 is the 4th element */
}

div:nth-child(5):nth-last-child(5) {
  /* The middle element in a set of 9 is the 5th element */
}

Or with Sass:

@for $i from 3 through 5 {
    div:nth-child(#{$i}):nth-last-child(#{$i}) {
        /* The middle element */
    }
}
like image 24
Thomas Higginbotham Avatar answered Sep 18 '22 07:09

Thomas Higginbotham