views:

44

answers:

3

I have an element like this:

<div id="content" style="border: 2px solid black">
</div>

And through JQuery I add some new stuff:

$("#content").append($('<div></div>').addClass("box"));

where

.box { margin: 10px; padding: 10px; border: 1px solid black }

But the outer div does not resize when I do this, so I get an inner box that is sticking out of a solid outer box. How can I get the outer box to resize itself when I add this inner box?

+1  A: 

try this:

js

$('#content').append('<div class="box">&nbsp;</div>');

html

<div id="content" style="border:2px solid black;overflow:hidden;">
</div>

I hope his help!

Mouhannad
Yeah the `overflow: hidden` did it, even without the JS change. Can you explain why?
luqui
@luqui Likely because you were floating the `.box` elements. It's a CSS problem, not a Javascript one.
Yi Jiang
@Yi Jiang, huh, yep, I was. I guess I still don't grok CSS.
luqui
yes its just a css issue here. i changed the js as well to show you a slightly better way of doing the same thing. i should've mentioned it :)
Mouhannad
`$('content')` should be `$("#content")`
Peter Ajtai
ahh yeah thanks!
Mouhannad
+2  A: 

Correct the selector if it's not a typo

$("#content") // id="content" (correct)
$("content")  // tagName = content

And change the display of the div to inline-block

#content {
    display: inline-block;
}

Then the div will not occupy the whole row.

BrunoLM
How cross browser is `inline-block`?
Peter Ajtai
@Peter: Any browser and for IE8+. IE7 might support it, I use it on a website and it works. This list say it's incomplete for IE7-. http://www.quirksmode.org/css/display.html
BrunoLM
A: 

#content is not resizing, since it's width is probably set in your CSS.

Either make it wider, or specifically size it appropriately.

Looks like #content must be over 40px wide, since the inner div has 10 margin and 10 padding, which is 20 on the left and 20 on the right.

So, something like:

$("#content").css("width","100%").append($('<div></div>').addClass("box"));

Or better yet, set up your CSS at the right width to begin with:

#content { width: ... ; }

If you are floating .box within #content then set the overflow of #content to auto(or hidden), otherwise the outer box doesn't "see" the floating inner boxes:

#content { overflow: auto; }
Peter Ajtai