Ahmed_K Ahmed_K - 9 months ago 38
CSS Question

CSS float causing element to overlap

I am a little confused, and would appreciate some help.

I'm looking at the article on float at MDN, and I copy and paste their example and change it a little, and it comes out how I would expect it to - the floated element is to the left of the next element.

However, I then create a second test in jsfiddle, and this time the floated element is on TOP of the next element.

(Please see the snippets).

Float to the left:

float: left;
margin: 0;

This is row 1 of some text.
This is row 2 of some text.
This is row 3 of some text.
This is row 4 of some text.

Float on top:

<div style="float: left; height: 100px; width: 100px; background: blue"></div>
<div style="height: 200px; width: 200px; background: orange"></div>

Can someone please explain to me what exactly is going on?

Answer Source

If you add a coloured background to the pre elements in your first example, then it should become clear: float affects text wrapping, but does not fundamentally change the flow of the page or change the size of elements.

If you added text to your orange box in example 2, you should see that it is wrapped.

Edit: here's a demo: https://jsfiddle.net/tj1appLf/