Wrap parent div around floated elements

I'm trying to get a div to wrap around a dynamic number of children and I would like to do this without setting a value for the width of the parent.

I have content wrapping floating on both child and parent, my problem is when the children are wrapped to the next line, there is free space left to the right, and I would like the parent to wrap tightly.

I created a demo here: http://jsfiddle.net/UMgct/4/

#parent shows the current behavior, I would like it to behave like # parent2 and # parent3, but without setting the width explicitly. I can see why the behavior for #parent is correct, I just don't see a way to get the behavior I would like.

Any ideas would be much appreciated

+3


source to share


1 answer


First, you must change "parent" and "child" as classes instead of IDs. IDs must be unique IDs, and 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);
});

      

+1


source







All Articles