There are times where it would be great to apply a given style to the 2nd, 3rd, 4th, etc. element of a parent. This is a simple task with jQuery. But if you have no other need for jQuery, other than this, why load it into your site.

If you only need to grab element 2 through 6 or so, this method is not super sloppy. Any further, and it really looks "hacky".

The magic here is the next sibling selector (+). You may have been familiar with it, but perhaps never considered using it in this way.

To get the 2nd element:

[parent selector] [child selector]:first-child + [child selector] // 2nd element
[parent selector] [child selector]:first-child + [child selector] + [child selector] // 3rd element

[parent selector] [child selector]:first-child + [child selector] + [child selector] + [child selector] // 4th element

 

For example, to get the 2nd, 3rd, 4th elements in a list:

ul li:first-child li /* 2nd list element */
ul li:first-child li + li /* 3rd list element */
ul li:first-child li + li + li /* 4th list element */

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *