jQuery - Divide width of the wrapper to the number of div`s inside
I need some help. I have a div wrapper and some other div's inside that will be added dynamically. The number of div's inside will be random so I need a script that will know how many div's are inside and which will be the width of the div's to fit in the wrapper perfectly.
<div id="wrapper">
<div class="block">A1</div>
<div class="block">A2</div>
<div class="block">A3</div>
<div class="block">A4</div>
<div class="block">An</div>
</div>
<style>
#wrapper {width:1000px;}
div.block {margin:0 0 20px 20px; border:1px solid #ccc;}
</style>
If you can consider the margins and border will be great! Thank you!
This is my script. It`s good, but not good handling the margins.
var ct = $('#wrapper').children().size();
var dw = $('#map').width() / (ct) - 25;
$("div.block").width(dw);
T开发者_StackOverflowhanks to the answers below I made the script work! Thank you all!
Check out the jsFiddle: http://jsfiddle.net/UTaSg/
You might have some extra space left because I round the decimal extra space down.
The script can easily be improved by adding the extra space left of the decimals the the first or last element.
You could do something like this, given that I've understood you correctly and each "div.block" has the same width:
var $blocks = $('#wrapper .block');
$('#wrapper').css('width', $blocks.length * $blocks.first().width(true));
精彩评论