Share via:

The Float two Divs Next to one div Problem

Two left-floated divs placed next to a right-floating div will cause the right-div to get pushed down.

346 views
d

By. Jacob

Edited: 2017-03-12 14:53

In a float based two column layout, I recently had two divs next to one div, totaling 3 divs. One floated right, the other two was floated left. This unexpectedly caused the right floated div to be pushed below the first left floated div.

The problem is likely caused by how CSS defines floated elements, but can be easily solved by using an additional wrapper.

Usually, when this happens for two floated divs, it will be caused by incorrectly clearing floats. Typically a div with clear:both; can also cause it.

Below screenshot shows the problem in my case:

Screenshot showing two floated divs next to one div, where one is being unexpectedly pushed.

The solution is to use a wrapper

The solution is to create one or more wrapper divs. For example, you could create one to contain all left column elements, and another to contain all the right column elements.

Alternatively, you could simply use absolute positioning for the right column, but it is probably easier to simply have a wrapper.

In this case, I choose to fix the problem using a single wrapper for the left floated elements:

<!DOCTYPE html>
<html lang="en">
  <head>
   <title>Test</title>

   <style type="text/css">
    #column1 {height:200px;background:gray;}
    #column1a {height:100px;background:yellow;}
    #wrapper {float:left;height:300px;width:70%;}
    #column2 {width:28%;float:right;background:black;height:300px;}
    
   </style>

  </head>

  <body>
   <div id="wrapper">
    <div id="column1"></div>
    <div id="column1a"></div>
   </div>
   <div id="column2"></div>
  </body>
  
</html>

Comments