detach and append resizing issue

detach and append resizing issue

I have the following scenario:

<div>
  ...
  <div id=" div1" style="width:50%; overflow:auto">
    <div id=" div2" style="width:100%; overflow:auto">
      ...
    </div>
  <div>
  ...
</div>

I want to detach div2 from div1, create div3, append div2 to div3, and then append div3 to div 1, as follows:

<div>
  ...
  <div id=" div1" style="width:50%; overflow:auto">
    <div id=" div3" style="width:100%; overflow:auto;padding:10px">
      <div id=" div2" style="width:100%; overflow:auto">
        ...
      </div>
    </div>
  <div>
  ...
</div>

The simplified code is as follows:

        $contents = $("#div1").contents.detach();
        $div3 = $("<div />").css({ "overflow": "auto", "padding": "10px" }).append($contents);
        $("#div1").append($div3);

There's additional logic, but this is the gist of it.

The problem is that, let's say I inspect the DOM just before the detach/reattach, and that the div1 width equals the div2 width equals 500px (for simplicity).

After I execute the code, div1 width is still 500px, AND div2 width is also still 500px, AND div1 has overflow equal to the size of the padding that we introduced with div3 (i.e. 20px). So the horizontal scroll bar appears.

div2 didn't resize to fit its container. Allowing for the padding, div2 should have a width of 480px and there should be no overflow.

Do I need to force a resize on div2? What am I doing wrong?

Thanks.