scale floated content to fill container
I have an HTML div with fixed width and height, containing nested divs arranged with 'float: left'. I'd like to scale the nested divs so they fill the container (with left over space following the final nested element as usual. In other words, I'd like the nested elements to be as large as possible without overflowing the container.
Sample starting point:
<div style="position: relative; background-color: blue; border: 1px solid yellow; width: 650px; height: 500px; margin: auto;">
<div style="position: relative; background-color: red; border: 1px solid magenta; width: 200px; height: 150px; margin: 5px; float: left;"></div>
<div style="position: relative; background-color: red; border: 1px solid magenta; width: 200px; height: 150px; margin: 5px; float: left;"></div>
...
</div>
(styles inlined for brevity)
Th开发者_StackOverflow中文版e content divs must be resized with their aspect ratio intact; neither the number of divs nor the size of the container are known in advance.
Since CSS doesn't provide a means to auto-size floated content in this manner, I'm doing it in JavaScript, but can't find a suitable algorithm for calculating the target size of the content divs; I suspect I need to do something clever with the relative aspect ratios of the container and content elements, but I can't think of anything that would work...
You can do this using only CSS, but only in standards-compliant browsers (so, not IE7 or lower).
Set your containing div to display: table-row;
Set each of your nested divs to display: table-cell;
Hope that helps a little :)
You could count the number of floating divs, divide the container width by them, then calculate a percentage for the width.
精彩评论