overexchange
overexchange

Reputation: 1

How inline elements float?

In the below html code,

<body>
        <p>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
          eiusmod tempor incididunt ut labore et dolore magna aliqua. <img src="LittleBrain.jpg"> 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.
        </p>

        <div><img src="LittleBrain.jpg"></div>
  </body>

img inline element has float property, as show below,

img[src="LittleBrain.jpg"] {
  float: left;
  padding: 10px;
}

The layout is as shown below.

enter image description here

Below is the output rendered on browser,

enter image description here


My question is:

As per the browser output, I could not understand the behavior of floating element img and its position in the html document flow.

As per my understanding, block level element(say div) float, as shown below, in 3D view browser,

enter image description here

In the above given code, How inline element(img) float? 3D view would help me understand the behavior of floating inline elements.

Upvotes: 2

Views: 833

Answers (1)

Oriol
Oriol

Reputation: 288680

Be aware floats do become block-level. So the answer is:

inline-level floats behave exactly like block-level floats

The observed behavior might have surprised you, but that's not due to the floating being (presumably) inline, it's due to the surrounding contents being inline.

See the float rules. A float is always placed as hight as possible, but

  • A floating box's outer top may not be higher than the top of its containing block. When the float occurs between two collapsing margins, the float is positioned as if it had an otherwise empty anonymous block parent taking part in the flow.
  • The outer top of a floating box may not be higher than the outer top of any block or floated box generated by an element earlier in the source document.
  • The outer top of an element's floating box may not be higher than the top of any line-box containing a box generated by an element earlier in the source document.

When a float is mixed with blocks, it's usually limited by the first two rules. But when you mix it with inline elements, then it's the last one.

In your case, you place the float at the middle of the text in the second line. Therefore, its top will be aligned with the top of the second line.

And then, as usual, the float will be pushed to the left, even if that means it might visually appear before some text which preceded it in DOM order.

Upvotes: 5

Related Questions