Add a margin to each element of class 2, 5, 8, 11, etc.

I have a webpage populating with a variable number of the same class elements. I want to set the left and right margins for every second, 5th, 8th, 11th, etc. Classes (if any).

Is there any way to achieve this using javascript? I do not want to use the css3 child selector as it is not compatible with older browsers.

My divs are arranged as follows:

[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 each middle div to have a margin on the left and right.

Thanks.:)

+4
source share
3 answers

nth-child jQuery

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

: Fiddle

+5

.

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 do not want to use the CSS3 child selector, you will have to do this either server-side or JavaScript.

As you noted the answer with jQuery, I assume this is your preferred choice, so you can try something like:

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

Source: https://habr.com/ru/post/1526328/


All Articles