views:

30

answers:

3

Hi,

Is there a way to dynamically set a div width / make the width relative to the content - using jQuery? It has to be with a numerical value because otherwise, it doesn't work with the horizontal website layout I'm dealing with...

The div will only contains images with a defined width values.

Thanks.

A: 

a div will stretch to fit its container (however wide it may be) by default if it doesn't have a width explicitly set.

set the div to have display:inline-block; and it will stretch to fit its contents, which is what you seem to want.

see example here: http://jsbin.com/usuno4

Moin Zaman
A: 

Div widths are 100% of the containing element, unless you have styles affecting the div or the div is inside a inline element.

--

Can you give any more information on what exactly you're trying to accomplish. The question is a quick answer, but I believe you're looking for more.

Ryan Ternier
If it can helps, I'm rebuilding http://www.joliannelm.com/europe.html and I need a different width value on my div according to the images in it. Since I'm rebuilding the site in a CMS and I want to make it very easy for my client to edit it, I don't want to have a custom value to enter on each page.
Steve Forest
And I must use a value in px, otherwise, I can't have the horizontal scrolling in the browser...
Steve Forest
A: 

This is the solution I was looking for :

<script type="text/javascript">
var width = 0;
$('#page img').each(function() {
    width += $(this).outerWidth( true );
});
$('#page').css('width', width + 0);
</script>
Steve Forest