Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How make middle div to fill space between floating elements?

I have three div elements: left, middle and right. Left and right are fixed and floating. What I want is the middle div to fill the gap in between them.

This is my code:

<!DOCTYPE html> <html> <head>    <style>       * {border: dotted 1px red;}       #left {          width: 200px;          float: left;       }       #middle {          float: left;       }       #right {          width: 200px;          float: right;       }    </style> </head> <body>    <div id="left"  >  left   </div>    <div id="middle">  middle </div>    <div id="right" >  right  </div> </body> </html> 

Any ideas on how to do this? I tried different solutions but didn't manage to do what I want.

like image 732
Pithikos Avatar asked Mar 30 '13 23:03

Pithikos


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 keep my div one below another?

If you want the two div s to be displayed one above the other, the simplest answer is to remove the float: left; from the css declaration, as this causes them to collapse to the size of their contents (or the css defined size), and, well float up against each other.


2 Answers

The key is to restructure your html to have middle last, remove the float from the middle and replace it with overflow: hidden.

View fiddle example.

HTML

<div id="left"  >  left   </div> <div id="right" >  right  </div> <div id="middle">  middle </div> 

CSS

#left {     width: 200px;     float: left; } #middle {     overflow: hidden; } #right {     width: 200px;     float: right; } 
like image 185
ScottS Avatar answered Sep 18 '22 09:09

ScottS


I was able to replicate the issue and fix it using percentages instead of absolute values. Since you are looking for something flexible between the two elements this should work.

#left {     width: 20%;     float: left;     background: #ccc; } #middle {     width: 60%;     float: left;     display: block;     background: #ddd; } #right {     width: 20%;     float: right;     background: #bbb; }  

Here's a demo

like image 27
djthoms Avatar answered Sep 21 '22 09:09

djthoms