4

I have a webpage filling with a variabel number of the same class elements. I want to set a left and right margin to every 2nd, 5th, 8th, 11th etc. class (if present).

Is there a way to achieve this with javascript? I don't want to use css3 child selectors, because of it's non-compatibility on older browsers.

My divs are placed like this:

[div class="block"][div class="block"][div class="block"]

[div class="block"][div class="block"][div class="block"]

[div class="block"][div class="block"][div class="block"]

[div class="block"][div class="block"][div class="block"]

I want every middle div to have a margin left and right.

Thank you. :)

3 Answers 3

6

Try use nth-child selector from jQuery

$('div:nth-child(3n - 1)').css('margin-top', '10px')

Demo: Fiddle

1
  • Not sure what the implications of using this would be (probably none) but (3n - 1) will cause the first child to be -1 as the nth-child formula is ((3x0) - 1), ((3x1) - 1), ((3x2) - 1), etc
    – Dave Kirk
    Feb 11, 2014 at 11:07
0

Try this.

i = 2;
block(i);

function block(i) {

    $(".block:eq(" + i + ")").css({"margin-left":"10px" ,"margin-right":"20px" });

    i = i + 3;

    block(i);

}
0

If you don't want to use CSS3 child selectors, you'll have to do it on either the server side or using JavaScript.

As you have tagged the answer with jQuery I'm assuming that is your preferred choice, so you could try something like:

$('.block:nth-child(3n+2)').addClass('middle');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.