How to put spacing between floating divs?
I found a solution, which at least helps in my situation, it probably is not suitable for other situations:
I give all my green child divs a complete margin:
margin: 10px;
And for the surrounding yellow parent div i set a negative margin:
margin: -10px;
I also had to remove any explicit width or height setting for the yellow parent div, otherwise it did not work.
This way, in absolute terms, the child divs are correctly aligned, although the parent yellow div obviously is set off, which in my case is OK, because it will not be visible.
You can do the following:
Assuming your container div has a class "yellow".
.yellow div {
// Apply margin to every child in this container
margin: 10px;
}
.yellow div:first-child, .yellow div:nth-child(3n+1) {
// Remove the margin on the left side on the very first and then every fourth element (for example)
margin-left: 0;
}
.yellow div:last-child {
// Remove the right side margin on the last element
margin-right: 0;
}
The number 3n+1 equals every fourth element outputted and will clearly only work if you know how many will be displayed in a row, but it should illustrate the example. More details regarding nth-child here.
Note: For :first-child to work in IE8 and earlier, a <!DOCTYPE>
must be declared.
Note2: The :nth-child() selector is supported in all major browsers, except IE8 and earlier.