[css] How to put spacing between floating divs?

i have a parent div, which can change its size, depending on the available space. Within that div, i have floating divs. Now, i would like to have spacing between these divs, but no space to the parent div (see drawing).

enter image description here

Is there a way to do this with CSS?

Thank you

This question is related to css html

The answer is


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.


A litte late answer.

If you want to use a grid like this, you should have a look at Bootstrap, It's relatively easy to install, and it gives you exactly what you are looking for, all wrapped in nice and simple html/css + it works easily for making websites responsive.


I'm late to the party but... I've had a similar situation come up and I discovered padding-right (and bottom, top, left too, of course). From the way I understand its definition, it puts a padding area inside the inner div so there's no need to add a negative margin on the parent as you did with a margin.

padding-right: 10px;

This did the trick for me!


Add margin to your div style

margin:0 10px 10px 0;

http://www.w3schools.com/css/css_margin.asp


Is it not just a case of applying an appropriate class to each div?

For example:

.firstRowDiv { margin:0px 10px 10px 0px; }
.secondRowDiv { margin:0px 10px 0px 0px; }

This depends on if you know in advance which div to apply which class to.