Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floated queries

Tags:

html

css

Consider the following code:

<div style="width:250px;background:red;">
  line1
  <div  style="width:auto;background:green;margin-left:10%;margin-right:10%;" >
     line2
  </div>
 </div>

and its results: enter image description here

The above is absolutely understandable to me.

Now, this code:

<div style="width:250px;background:red;">
line1
<div  style="float:left;width:auto;background:green;margin-left:10%;margin-right:10%;">
     line2
</div>
 </div>

and its results: enter image description here

I cannot explain two things. First one: why does the inner div change position? Since floating does not affect previous elements, I'd expect text "line1" would not wrap next to green div! Second one: Float property does not accept width:auto? Why green div shrinks?

Thank you

like image 305
Unknown developer Avatar asked Mar 09 '26 23:03

Unknown developer


1 Answers

A document flow refers to block elements rendering in a vertical direction, inline elements rendering in a horizontal direction, and all elements rendering in the order they are encountered.


Excerpt from w3.org - Floats and clearing

<p>This is a very simple document.</p>
<p>It consists of <em>two</em> paragraphs.</p>

Here is a screen shot of that document with an overlay that shows the two block boxes generated by the p elements and the inline box generated by the em element.

enter image description here


Float alters the way that the element is rendered in the document flow. Unlike position absolute, it will not entirely remove the element from the flow. It essentially makes it similar to an inline block element with the caveat that it will "float" over other non floated elements in the direction indicated as far as possible.

As a result, the line2 element does not cause a new line, and takes precedence in rendering over line1. Because of this you end up with a line2 element coming before line1.

As for the width, since line2 is now inline-ish its width is just to contain the content. When auto is used, it has no affect on this.

However, there is a caveat. If width:200px; were used on line2 then that would make the float be placed on the next line because that was "as far left as possible" since there was not enough space to float a 200px element (+20% for margin) in the previous line. Because line1 was already there, and with 200px and 20% margin of the containing block (50px), line2 would not be able to fit on the same line.

enter image description here
fiddle for image

like image 99
Travis J Avatar answered Mar 12 '26 12:03

Travis J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!