Steve Forest
Steve Forest

Reputation: 97

div width relative to content

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.

Upvotes: 1

Views: 5792

Answers (3)

Steve Forest
Steve Forest

Reputation: 97

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>

Upvotes: 2

Ryan Ternier
Ryan Ternier

Reputation: 8814

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.

Upvotes: 1

Moin Zaman
Moin Zaman

Reputation: 25455

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

Upvotes: 4

Related Questions