1

I have this sample code:

<html>
<head>
</head>
<body>
<div style="float:left;" id="1">
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
</div>
<div style="border:1px solid black;" id="2">
bbbbbbbbbbbbbbbbbbbbbbbbbbb
</div>
</body>
</html>

The contents of div 2 is placed left of the contents of div 1 (fine), but the border of div 2 contains div 1. This happen in all tested browsers (Firefox 26.0 and IE8).

Demo

Can you please explain what is going on?

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
Lesto
  • 2,260
  • 2
  • 19
  • 26

1 Answers1

2

Because you aren't floating another div - Demo

And since it's not floated, it will take entire horizontal space, also it won't shift down as you aren't clearing your floats.

So what happens is the floated div just sits to the left, making your non floated div wrap around it..

If you move the order of your div in the markup, you will understand what I meant - Demo So, as you see, the top div takes all the horizontal space available, whereas the other div sits on the left, won't take entire horizontal space as it's floated to the left, so since you have the floated div first and next is non floated div it will take up 100% space, but will wrap around the floating div since you haven't cleared it, so you should float the next div as well.

The same effect can be achieved using display: inline-block; as well.

For more information on how floats work, refer my answer here

<div style="float:left;" id="1">
    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
</div>
<div style="border:1px solid black; float: left;" id="2">
    bbbbbbbbbbbbbbbbbbbbbbbbbbb
</div>
Community
  • 1
  • 1
Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
  • this indeed is the right answer, how comes the floating div is inglobed in the other one thought? – Carlo Moretti Feb 13 '14 at 13:21
  • 1
    @Onheiron I explained :) you can read my other answer which covers floats in detail, when you float them, they get out of the flow, so the next element will move up... unless the floated element is cleared, so you feel the `div` is inglobed :) – Mr. Alien Feb 13 '14 at 13:23
  • 1
    @lesto it is out of the document flow but not like `position: absolute;` so it will keep it's space reserved, nudging the text of the div to wrap around, if you expect overlay, than here you go http://jsfiddle.net/9LdTa/4/ :) – Mr. Alien Feb 13 '14 at 13:36
  • Thank you, as last request how do you know about this thing? there are paper about this or you readed the RFC? – Lesto Feb 13 '14 at 13:45
  • 1
    @lesto Studying, experience, you can refer articles online and try and keep testing :) you can read one good article [here](http://coding.smashingmagazine.com/2009/10/19/the-mystery-of-css-float-property/) – Mr. Alien Feb 13 '14 at 13:48