In terms of memory usage, which one is heavier on the browser - is the latter heavier because it has to find every divs after the 4th one?
Who knows? You'd have to have access to the source code of any browser engine(s) you're interested in, and I wouldn't be surprised if it differed across browsers — it's an extremely low-level implementation detail. And even if you did have access to the source, this information wouldn't be useful to you unless you're a browser developer.
In terms of browser compatibility, which one has more support - does the latter have more browser supports (IE8 only partially support :nth-last-child
)?
In terms of browser compatibility, they are completely identical. Internet Explorer 8 doesn't support :nth-last-child()
at all. And there are no known versions of any browser that support either :nth-child()
or :nth-last-child()
but not both.
If you need IE8 support, this technique will let you match every div after the 4th one without using :nth-child()
or :nth-last-child()
— the only CSS3 selector that's used is the ~
combinator, which IE8 does support:
div:first-child + div + div + div ~ div
This assumes you have exactly 10 divs, but then so do the two selectors you propose.
Which should I choose?
Well, even if you can guarantee that there will only ever be exactly 10 divs, no more, no less and no other children, div:nth-last-child(-n+6)
still makes more sense as it does exactly what is described: "match the last 6." div:nth-child(4) ~ div
doesn't make it as obvious, since what it's really saying is "match any div after the 4th." It just happens to pick up 6 of them by coincidence.
It also carries less specificity, in case that's important.