Wrapping a parent div around floated elements

Go To StackoverFlow.com


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

2012-04-03 21:36
by user7009
Are you saying, you'd like the red boxes to remain on the same line even if they don't fit in the monitor space - henryaaron 2012-04-03 21:41
No, I'd like them to wrap onto the next line, I'd just like to remove the space to the right of the last child element on each line i.e in the example I'd like the green background to never be more than 10px to the right of the last child on the first lin - user7009 2012-04-03 21:47
How many are going to be displayed per line? Do you tell it how many or is there some way for the browser to determine how many to put on one line - JamesSwift 2012-04-03 22:08
You're inheriting width: 868px;. What about using width=0 - Robert Smith 2012-04-03 22:14
Each element will have a fixed width and the parent div is filling the viewport so the number per line will be dynamic based on what resolution you're viewing the page at. So if I have three child elements at 500px each on a 1280x720 viewport there will be two children on each line with a gap on the right side of the parent of 280p - user7009 2012-04-03 22:17


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);
2012-04-03 22:29
by JamesSwift
Thanks, you're right I should be using classes, I just threw that together quickly as an example without thinking.

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

For shure, ids MUST be unique, but class CAN BE multiple - smonff 2012-04-03 22:45