treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Wrapping a parent div around floated elements

  • 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
  • Here's a solution using percentage widths. I'm not sure if IE will support this method however.

    http://jsfiddle.net/UMgct/5/
  • Thanks for the quick reply, that's not quite what I'm after though. I'd like to keep the child elements at a fixed width and fit as many on one line as the viewport will allow without the parent div expanding too far out to the right when the children flow over onto a new line.
  • Is the consensus that this is impossible? I have it working using javascript but I'd prefer a pure css solution if possible
  • Not sure if I understand you but check out how I have the clear:both;
    http://jsfiddle.net/UMgct/46/
  • Thanks for the tip, I've now condensed it down into just placing it in the css, I've updated my example to show what I'd like here: http://jsfiddle.net/UMgct/48/ .parent is how I'd like it to behave, .parent2 is how it currently behaves. Like I say, I'd prefer to not use javascript if at all possible
  • you could use media queries

    this example assumes the children are known width