I have the following setup:
<div id="wrapper">
<div class="column1"></div>
<div class="column3"></div>
<div class="column2"></div>
</div>
#wrapper {
position:absolute;
}
Every "column" has a different width and a float: left. So the 3 columns together are, let's say, 900 pixels wide; but I want the wrapper to get it automatically if I put a new column.
So I want to get and set the wrapper's width based on the columns it contains using JavaScript.
4 Answers
$("#wrapper").width(function() {
var width = 0;
$(this).children('[class^="column"]').each(function() {
width += $(this).width();
});
return width;
});
Don't use floats, but display:inline-block (Demo)
var w = 0;
$('#wrapper > div').each(function(index) {
w += $(this).outerWidth();
});
$('#wrapper').width(w);
Here's a fiddle:
var totalWidth = 0;
$("div#wrapper > div").each(function(index) {
totalWidth += parseInt($(this).outerWidth(true), 10);
});
$("div#wrapper").width(totalWidth);