Reputation: 684
Here is my JSFIDDLE.
Scenario - Here The individual divisions one,two,three are dynamic. The number of individual blocks might increase.
I want to find the total width of the those 4 blocks. And I want to assign that width to the above Grey block.
So Whenever new blocks are added, The above grey block's width should be equal to the total width of the blocks.
<div class="head">
<div class="top"></div>
<div class="body">
<div class="body-inner">
<div class="w one"></div>
<div class="w two"></div>
<div class="w three"></div>
<div class="w four"></div>
</div>
</div>
Upvotes: 1
Views: 82
Reputation: 155
Using a .container, clearfix and inline-block
CSS
.container {
display: inline-block;
}
JSfiddle: http://jsfiddle.net/ew4Y3/10/
PS basically the same as Danield's answer
Upvotes: 0
Reputation: 6996
You can use jquery's
outerWidth() - Returns the width of the element, along with left and right padding, border, and optionally margin, in pixels.
$('document').ready(function () {
var x = 0;
$('.w').each(function () {
x += $(this).outerWidth() + 10;
});
//10 because first-child does not have margin left and last-child does not have margin right
x -= 10;
$(".top").css("width", x + "px");
});
Upvotes: 0
Reputation: 6646
var onew=$('.one').width();
var twow=$('.two').width();
var threew=$('.three').width();
var fourw =$('.four').width();
$('.body-inner').width( onew + twow + threew + fourw );
Upvotes: 0
Reputation: 125443
Why not move your top div into the body-inner div, then just set:
.body-inner
{
display: inline-block;
}
FIDDLE (no JS required)
Upvotes: 2
Reputation: 85545
You need to wrap your code inside ready function:
$(document).ready(function(){
var x = 0;
$('.w').each(function () {
x += $(this).width();
});
alert(x);
var y = $('.body').width();
alert(y);
});
Upvotes: 0
Reputation: 4414
You can calculate width of each block and assign that width to .top
.
I've made here function refreshWidthCalculation()
, that you need to call everytime if you are adding new <div class="w"></div>
Here is updated jsFiddle
var w=0;
$('document').ready(function() {
refreshWidthCalculation();
});
function refreshWidthCalculation(){
w=0;
$(".w").each(function(){
w+=$(this).width();
});
$(".top").width(w);
}
Upvotes: 1