Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put spacing between floating divs?

Tags:

html

css

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

like image 870
ghost23 Avatar asked Oct 06 '11 15:10

ghost23


People also ask

How do I add a space between floating divs?

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.

How do I put vertical space between two divs in HTML?

a (the fixed one) to the top of the page, add top: 0; and if you want it to stay on top of the rest of the content, include z-index: 2; . In order to add spacing between div.

How do I get rid of the white space between divs?

This is caused by the fact your browser will render the DIV's inline and as with words, they are separated by spaces. The width of the space is determined by the font-size, hence an easy trick is to set the font-size of your containing element to 0 and then reset the font-size in your inline divs.


2 Answers

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.

like image 89
ghost23 Avatar answered Oct 06 '22 14:10

ghost23


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.

like image 42
Coreus Avatar answered Oct 06 '22 13:10

Coreus