Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why `float:left` doesn't work with a fixed width?

Tags:

css

css-float

I have two divs on a webpage and I would like both of them to have a fixed width and would like the first div to be floated to the left of the second div.

This sounds so simple that I though the following Markup and CSS would give me the desired result:

<div class="left">Content</div>
<div class="right">Content</div>

div.left {
    float: left;
    width: 200px;
}

div.right {
    width: 200px;

This doesn't work as expected, instead the right div appears on the next line as though it wasn't floated. This is best explained in this example webpage:

Example of the Problem

My question is WHY this doesn't work as expected? Not how to fix it.

Notes:

  • Please make sure you fully understand how floats work before answering this question.
  • Please make sure you view and understand the examples.
  • Both elements must be block, not inline.
  • I understand all fixes/hacks to make this work. I want to know why it doesn't work.
  • This appears to only work correctly in Opera.
  • Backing up your answer with documentation is required.
like image 304
GateKiller Avatar asked Feb 11 '11 11:02

GateKiller


2 Answers

It seems to me that it is the simple rule that blocks, unless floated, always start a new line. w3.org/TR/CSS2/visuren.html#block-formatting section 9.4.1 –

like image 108
Elroy Flynn Avatar answered Sep 21 '22 14:09

Elroy Flynn


 div.left {
     float: left;
     width: 200px;
    height:200px;
    background:red;
 }

 div.right {
    float:right;
     width: 200px;
     height:200px;
    background:blue;
}

see http://jsfiddle.net/3kUpF/

Alternatively, if you want them side by side then you can float:left on both see http://jsfiddle.net/3kUpF/1/

like image 35
Hussein Avatar answered Sep 24 '22 14:09

Hussein