In example below I have three rows(divs marked with .row) and set width to 33% to have them the same size and fill the whole area. The problem is that these .row divs are dynamically generated and sometimes instead of three divs could be four or two divs. In that case how to set width? For example if theer are two divs a width should be 50% for both.
<div class="membership-table">
<div class="row">
<div class="title">
Personal One Year membership
</div>
</div>
<div class="row">
<di开发者_开发问答v class="title">
Lifetime membership
</div>
</div>
<div class="row">
<div class="title">
Business One Month membership
</div>
</div>
</div>
.membership-table { text-align: center; }
.membership-table .row { display: inline-block; margin: 0; padding: 0; width: 33%; }
.membership-table .title { color: #c30000; font-size: 15px; font-weight: bold; }
The simplest way would be to use Javascript, to count the rows and edit the sizes accordingly. I tend to use jQuery, and would use something like the following:
var rows = $('.membership-table .row');
rows.width((100/rows.length)+'%');
The other way to do it is server-side: when the server side script loops through the rows, add a classname that is defined in the CSS to be a certain width. For example, in PHP:
$rows = [row1, row2, row3...];
$count = count($rows);
foreach ($rows as $row) {
echo '<div class="row count'.$count.'">';
echo ' <div class="title">';
echo ' Personal One Year membership';
echo ' </div>';
echo '</div>';
}
Then, in your CSS, add in the following:
.count1 { width:100%; }
.count2 { width:50%; }
.count3 { width:33%; }
.count4 { width:25%; }
.count5 { width:20%; }
And so on, until you reach the maximum number of columns you might have. You'll need to put in some sanity checks, to make sure your 'count' classes don't go too high, but something along those lines would work.
Unfortunately there's not a way in CSS to do maths on the fly. It's a CSS3 module (http://www.w3.org/Style/CSS/specs#math) but has very little support or impetus behind it in any of the major browsers.
If you are looking for a pure CSS solution. You will need css3 box-flex: http://designshack.co.uk/articles/css/farewell-floats-the-future-of-css-layout/
But this will not work in old browsers like IE.
The other solution would be to do it with jQuery for example:
$(".membership-table .row").css( "width", 100 / $(".membership-table .row").length + "%" )
This will set the width of each of your rows to 100 / numbers of rows.
demo: http://jsfiddle.net/4zGxZ/1/
Can you use a Jquery on the page? If yes:
I have edited, because divided zero can't be possible ( if no rows in it)
var divLength = $(".membership-table .row").length;
if (divLength)>0
{
var divPercentage = 100/ divLength;
$('.membership-table .row').css('width',divPercentage+'%');
}
精彩评论