Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is width required to float two divs side by side using float:left property?

Tags:

html

css

When I first learned HTML, I was told that if you want to float 2 divs side by side using float:left, you must set a width on those two elements. This is because a div, by default, is a block element, which will take up the full width it has available to it.

As I've built various projects, I have come across cases where floating did not work without setting a width, but then in other cases, it seems a width is not needed, and the float itself will restrict the elements width.

For example, the following fiddle shows two elements floating side by side only using the float property, no width was required.

<style>
    .left{
        background-color:yellow;
        float:left;
    }

    .right{
        background-color:green;
        float:left;
    }
</style>

<div class="left">
    Floating left
</div>
<div class="right">
    Floating left
</div>

However, in other similar scenarios that I can't seem to reproduce right now, applying the float property to two divs does not allow them to float side by side unless a width is a set for both.

Am I losing my mind or is there some scenarios for which this behavior varies?

like image 754
flyingL123 Avatar asked Apr 22 '15 02:04

flyingL123


2 Answers

When set float:left or float:right on an element, it forces the creation of a new block formatting context, and it behaves similarly to inline block level, the width and height are dynamic (determined by the content).

like image 148
Stickers Avatar answered Oct 19 '22 19:10

Stickers


... a block element, which will take up the full width it has available to it.

A non-replaced block element in normal flow will take up the full width it has available to it. This requirement is stated at http://www.w3.org/TR/CSS2/visudet.html#blockwidth

A floated element is not in normal flow, so that rule does not apply. Instead, float widths are determined according to their own rules, stated and described at http://www.w3.org/TR/CSS2/visudet.html#float-width. This says that when a floated element has a computed width of "auto", its used width is determined using the shrink-to-fit algorithm.

Note that the shrink-to-fit algorithm is also used for other types of layout, including non-replaced inline-block elements and table cells, but in other respects, such as vertical alignment, the layout behaviour of those elements is quite different from that of floats.

like image 35
Alohci Avatar answered Oct 19 '22 18:10

Alohci