Sunday 16 October 2016

class - CSS selector for certain position of matched classes



I have the following divs:






//this



//this
//this










Is there a CSS selector that lets me select .a elements situated in 3rd,4th and 5th position of the .a matched results?



Something similar to eq() in jQuery.



:nth-child() is not of help here as this is just a simplified case.



This is a fiddle with the results using jQuery. I want to know if there is a solution using just CSS.


Answer



No, there is no equivalent to jQuery's :eq() in CSS. In plain English, there is no selector for the nth element matching a complex selector (in your example, the 3rd, 4th and 5th elements matching the selector .a).




Just for the sake of completeness (because someone is going to say "well, actually..."), the specific elements are, of course, reachable with



.c:nth-child(1) > .a:nth-child(3), .c:nth-child(2) > .a:nth-child(1), .c:nth-child(2) > .a:nth-child(2)


But that assumes that is exactly how your markup appears, which is seldom ever a realistic assumption to make, especially if the page is dynamically generated.



In the very unlikely event that your markup is static and you can rely on the 3rd, 4th and 5th .a elements being in those exact positions, by all means use the selector above. But if their positions or structure can vary, then you will need other ways to identify them in CSS, for example with an additional class name.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...