Reputation: 171
I currently have the following HTML:
<div class="clearfix">
<div style="width:33%;float:left">content</div>
<div style="width:33%;float:left">content</div>
<div style="width:33%;float:left">content</div>
</div>
When there are 3 divs on the one line, and because I specified a percentage width for each, they all fully occupy the width of the parent width. What I am trying to achieve is to have the floating divs auto-adjust their widths (i.e. without hard-coding a percentage width) depending on how many divs are present on the line. For example, if there are 2 divs, then each would occupy half of the entire width of the parent (i.e. 50%). If there are 3 divs, then 33%.
Is this possible with floating divs? If not, what other ways can I use to achieve this type of fluid layout? I looked into making the parent use a 'table' display and the inner divs a 'table-cell' display, but then the parent stopped occupying 100% of the width available to it.
Upvotes: 1
Views: 6080
Reputation: 16393
You can use jQuery to achieve the dynamic changes in the style:
var divcnt = $(".clearfix div").length;
var widthInPercent = 100.0 / divcnt;
$(".clearfix div").each(function() {
$(this).css("width", widthInPercent+"%")
});
For an example see this demo.
Upvotes: 1
Reputation: 50563
Your table approach worked fine for me, just remember to remove the float:left
from the children divs, see my working demo.
Upvotes: 5