简体   繁体   中英

Add margin to every 2nd, 5th, 8th, 11th etc. class element

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. :)

Try use nth-child selector from jQuery

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

Demo: Fiddle

Try this.

i = 2;
block(i);

function block(i) {

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

    i = i + 3;

    block(i);

}

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM