Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DIV container size to width of wrapped floating contents

I'm trying to create a container div with a width only of the size of the contents. I have that part working correctly by using float: left on the container. Here is what I have so far.

HTML

<div class='container'>
    <div class='floater' style='background-color: #880000'>1</div>
    <div class='floater' style='background-color: #008800'>2</div>
    <div class='floater' style='background-color: #000088'>3</div>
</div>

CSS

.container {
background-color: #123456;
float: left;
}

.floater {
width: 300px;
height: 100px;
float: left;
}

The problem I'm having is when the floater divs get wrapped inside the container. I do want them to wrap, but I also want the width of the container div to resize accordingly. For instance, if your browser is 1000px wide, it all works fine and the container is 900px. However if you shrink the browser to something like 750px wide, the 3rd dive wraps to the next line, but the container is 750px wide; not the 600px I want.

Is the behavior I want possible? If so, how?

I made a Fiddle for everyone to see what I'm talking about Click Here

like image 395
krische Avatar asked Apr 30 '11 15:04

krische


1 Answers

That is beacause the width of the .container element is determined by the width of the page or the containing element. The containing element may or maynot be the html element depending on the browser. Basically you have the .floater elements having a fixed width of 300px x 100px (set explicity) and the .container element width and height is set implicity. Try something like this.

.container {width: 90%;}

This will cause the width of the .container element to be always less than that of the containing element. So If for example the containing element is html which has a width of 1000px, the width of the .containing element will be 90% of 1000px which will be 900px. If the html element is 750px, the .container element will be 90% of 750px which is 675px.

Also you may or maynot have problems with you code depending on what you have above, below and inside the .container element, since you have not cleared you floats. Try some thing like this

.container {overflow: auto;}
like image 74
Jawad Avatar answered Oct 05 '22 07:10

Jawad