Get and Set Wrapper Width Based on Its Content

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.

5

4 Answers

$("#wrapper").width(function() {
    var width = 0;
    $(this).children('[class^="column"]').each(function() {
        width += $(this).width();
    });
    return width;
});​
3

Don't use floats, but display:inline-block (Demo)

1
var w = 0;
$('#wrapper > div').each(function(index) {
  w += $(this).outerWidth();
});
$('#wrapper').width(w);
0

Here's a fiddle:

var totalWidth = 0;
$("div#wrapper > div").each(function(index) {
    totalWidth += parseInt($(this).outerWidth(true), 10);
});

$("div#wrapper").width(totalWidth);​
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest