Search code examples
csscss-float

Is float used for block or inline elements?


  1. Floats — Applying a float value such as left can cause block-level elements to wrap along one side of an element. Source

  2. The float CSS property places an element on the left or right side of its container, allowing text and inline elements to wrap around it. Source

So float is used to wrap block elements around another element or it is used to wrap inline elements around another element? Why is there a difference in two sources?


Solution

  • So float is used to wrap block elements around another element or it is used to wrap inline elements around another element?

    The most relevant part of the specification says:

    Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float did not exist. However, the current and subsequent line boxes created next to the float are shortened as necessary to make room for the margin box of the float.

    See this example:

    #float {
        float: left;
        outline: solid red 3px;
        width: 30%;
        padding: 2em;
    }
    
    #not-float {
        outline: dotted blue 3px;
    
    }
    <div id="float">Float</div>
    <div id="not-float">
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    </div>

    The div passes through the float (you can see the outlines overlapping) while the line boxes generated by the text inside it wrap around the float.

    Note that its about the boxes that are generated by the element and text, not the elements themselves.

    Why there is difference in two sources?

    Because MDN is:

    • Written by volunteers (you might consider reporting an issue or submitting a pull request) who are generally very good, but aren't perfect.
    • Trying to explain things in a more accessible way than the specification, and simplification can lose detail.