Lesto
Lesto

Reputation: 2299

Strange behaviour div and float:left

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?

Upvotes: 1

Views: 256

Answers (1)

Mr. Alien
Mr. Alien

Reputation: 157314

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>

Upvotes: 2

Related Questions