How make middle div to fill space between floating elements?

Pithikos picture Pithikos · Mar 31, 2013 · Viewed 24.2k times · Source

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.

Answer

ScottS picture ScottS · Mar 31, 2013

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;
}