-2

My observation is, float elements overlap on its previous elements, but in the below code, div element did not over lap body element.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>All selector</title>
        <style type="text/css">
            h3{
                margin: 0;
                heigth: 10px;
            }
            div, span, p{
                width: 80px;
                height: 40px;
                float: left;
                padding: 10px;
                margin: 10px;
                background-color: #EEEEEE;
            }
        </style>
        <script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.min.js">
        </script>
    </head>
    <body>
        <div>DIV</div>
        <span>SPAN</span>
        <p>P<button>BUTTON</button></p>

        <script type="text/javascript">
            var elementCount = $('*').css("border", "3px solid red").length;
            $('body').prepend("<h3>" + elementCount + " elements found</h3>");
        </script>
    </body>
</html>

Actual output is:

enter image description here

As per my understanding on float:left,

Expected output is,

enter image description here Why 3 float elements div, span & p are not overlapping on body element?

overexchange
  • 15,768
  • 30
  • 152
  • 347
  • @JaromandaX `clear:left;` is to make `div`, `span` & `p` does not have any element on its left. – overexchange Jan 01 '16 at 06:11
  • In addition to down vote, please explain the reason. This would help me, correct myself. – overexchange Jan 01 '16 at 06:17
  • you are getting confused with positioning, you should look up the difference between relative and absolute and how this is relevent to floats. In all honesty you shouldnt be using floats to position, you should be using flexbox. – marblewraith Jan 01 '16 at 07:51

1 Answers1

2

Floating element is shown floating against the content that follows it. There is no content after the div / span / p tags. Note: you are prepending the h3 tag to body. Try appending and see what output you get.

Vivek Athalye
  • 2,974
  • 2
  • 23
  • 32