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.

1480 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>

Tell us what you think:

  1. An in-dept look at the use of headings (h1-h6) and sections in HTML pages.
  2. Pagination can be a confusing thing to get right both practically and programmatically. I have put a lot of thought into this subject, and here I am giving you a few of the ideas I have been working with.
  3. The best way to deal with a trailing question mark is probably just to make it a bad request, because it is a very odd thing to find in a request URL.
  4. How to optimize image-loading and automatically include width and height attributes on img elements with PHP.
  5. HTTP headers are not case-sensitive, so we are free to convert them to all-lowercase in our applications.

More in: Web development