NW Tech
NW Tech

Reputation: 328

Finding a pseudo nth-child to apply CSS changes

I have a list of items that are floated left with a 20px right margin. Every 4th item does not have a right margin, therefore, the list items line up into 4 columns. I'm doing this by ussing the CSS nth-child(4n) selector for the list items

That works all fine and dandy, then I decided to apply filtering via the jquery isotope plugin, which messed things up a bit. Every 4th item still does not have right margin, but this applies to every item in the list.

What I need to do is figure out to find the 4th child on the screen, and apply the CSS rules. I'm sure this is probably done by some other java.

If showing any of the code, CSS HTML, or jQuery, would be helpful, let me know what. Any help would be greatly appreciated.

Upvotes: 1

Views: 188

Answers (2)

Spudley
Spudley

Reputation: 168695

This is harder than it sounds.

nth-child and nth-of-type selectors do not distinguish by whether an element is visible or even by checking additional selectors (eg you can't do it by looking at the classname).

Using nth-child(4n), you will always get the fourth/eighth/etc elements that are children of the selected parent; there is no way to filter it further except by type (nth-of-type).

Using nth-of-type(4n) is the same, but filters by the element type of the selected element. (eg if you select a div, then nth-of-type(4n) will give you the 4th/8th/etc div elements in the set, ignoring any spans, etc).

There is a CSS4 selector, nth-match() which would do what you're looking for, but unfortunately it isn't supported in any browser yet, and doesn't look likely to be any time soon.

So how can we do what you want in existing browser?

  • The easy option is to delete the hidden elements from the DOM rather than simply hiding them. Then your existing nth-child() selector will just work. Of course this isn't ideal if you need to toggle them in and out, but it is an option.

  • Use Javascript rather than CSS to select the elements. Maybe toggle a classname or something on the (4n) visible elements when you change the visibility of any of them.

  • Look for a polyfill library that implements the nth-match() selector.

Upvotes: 0

DaniP
DaniP

Reputation: 38252

The way with Jquery is evaluate just the :visible elements and then apply the sytle, like this:

$(document).ready(function(){
    $('div:visible').each(function (i) {
      if ((i+1) % 4 == 0) $(this).css('marginRight','0');
    });
})

You just need to change your selector and place it in the correct handler you want.

Check this Demo http://jsfiddle.net/QNDVP/.

Upvotes: 1

Related Questions