Skip to content

auto space between divs

An answer to this question on Stack Overflow.

Question

I have to create a web page with a big div (grey colored) and many divs (black colored) near it (float left).

At the moment I'm using a margin (margin-right) which divides the black divs. (I don't mind about the grey div because it's done.) My problem is that the most right div for each row must not have the margin-right because i haven't got any more space to give it. I can't create a specific class (margin-right: 0) for them because all the black divs will be added dynamically. Is there any solution to my problem?

Answer

You can style them using the nth-child selector. It has a special form (an+b) where a is the cycle size and b is an offset.

.blackboxes:nth-child(3n+0) {margin-right:0}
.blackboxes:nth-child(5n+6) {margin-right:0}
.blackboxes:nth-child(3n+6) {margin-right:5px}

You may need to make the 6 into a 7 to get things right.

Note that the final styling is meant to over-ride the first effectively isolating the first grouping of six black boxes.