I'm trying to get a div to wrap around a dynamic number of child elements and I'd like to do this without setting a value for the width of the parent.
I've got the content wrapping by floating both the child and parent elements, my problem is when the child elements wrap onto the next line there's free space left over on the right side and I'd like the parent to wrap "tightly".
I've set up a demo here: http://jsfiddle.net/UMgct/4/
#parent shows the current behaviour, I'd like it to behave like #parent2 and #parent3, but without explicitly setting the width. I can see why the behaviour for #parent is correct, I just can't see any way of getting the behaviour I would like.
Any ideas would be greatly appreciated
First off, you should change 'parent' and 'child' to be classes instead of IDs. IDs are meant to be unique identifiers, while classes can be used as many times as you want.
With that said, you can achieve what you want with JQuery (assuming the IDs are now changed to classes):
$(document).ready(function() {
var numPerLine = parseInt($(window).width() / $('.parent > .child').outerWidth(true));
$('.parent').width($('.parent > .child').outerWidth(true) * numPerLine);
});
With regards to your answer, that works perfectly, I was just wondering if there was any way to do it without javascrip - user7009 2012-04-03 22:40