Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove right margin on every fourth VISIBLE element using jQuery?

I have successfully used the jQuery :nth-child() selector to remove the right margin from every fourth element in a long list of div's. It looks like this:

$(".myDivClass:nth-child(4n+4)").css("margin-right", 0);

But the page is also open for user interaction (via jQuery) and one of the things that the user can do is hide/show elements. When an element is hidden, its style is set to "display:none". The elements are floated so if you remove one element in the middle of a row, an element from the row below will jump up, like this:

Problem with margin when an element is removed

My first thought was to redo the whole thing by first adding a margin to all elements and then remove it from every fourth visible element; something like this:

$(".myDivClass").css("margin-right","20px");
$(".myDivClass:visible:nth-child(4n+4").css("margin-right", 0);

But the second row does nothing and I don't think you can stack pseudo selectors like in the example above(?)

Is there a solution to this problem? Is there a better way to do this?

Thanks in advance!

/Thomas

like image 651
tkahn Avatar asked Jan 24 '11 15:01

tkahn


1 Answers

I know this isn't directly an answer to your question, but when I do similar things with floating a bunch of block elements with some spacing between them, I usually will keep the margin on all of them but make their parent container have (in this case) a negative margin-right equal to the spacing between the elements.

This way the parent will still fit where you want it but the children will just float as they should with the space they need.

like image 87
nemophrost Avatar answered Sep 27 '22 18:09

nemophrost