dkjain
dkjain

Reputation: 871

Floated div does not expand to full width of parent div. Why?

According to this excerpt from BrainJar.com's positioning article

For one, the box being floated should have a width defined for it, either explicitly or implicitly. Otherwise, it will fill its containing block horizontally, just like non-floated content, leaving no room for other content to flow around it.

However in the following code, this does not happen i.e. the floated div does not expand to it's parent containers full width and there are no width defined on floated div.

HTML

    <div id="container">
         <div id="aqua">aqua</div> 
         <div id="yellow">yellow</div> 
         <div id="pink">pink</div>
    </div>

CSS

#container { border:1px solid red} 
#aqua, #yellow { border:1px solid green; float:left;}   
#pink { width:150px; border:1px solid blue; }

I am interested in knowing the reason behind it.

Thanks

Upvotes: 0

Views: 900

Answers (2)

Asons
Asons

Reputation: 87191

Why it works in Brainjar.com is because the floats are filled with content, and as such they expand to its parent width if width is omitted on the floated element.

So the statement

Otherwise, it will fill its containing block horizontally, just like non-floated content, leaving no room for other content to flow around it.

will be wrong if the floated element is empty or with content less than to fill its container's width.

More about floats here: https://developer.mozilla.org/en-US/docs/Web/CSS/float

And filling your sample with more content show that it works like that.

#container { border:1px solid red} 
#blue, #aqua, #yellow { border:1px solid green; float:left;}   
#pink { width:150px; border:1px solid blue; }

#pink { clear: left }
<div id="container">
	 <div id="aqua">aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua aqua</div> 
	 <div id="yellow">yellow</div>
	 <div id="blue">blue</div>
	 <div id="pink">pink</div>
</div>

Upvotes: 1

Serge In&#225;cio
Serge In&#225;cio

Reputation: 1382

are you looking too fill the full width? Or do you want an explanation?

If you just want the full width just add width: 100%; to your floated IDs

Upvotes: 0

Related Questions