tags:

views:

57

answers:

2

Hi there,

I have a variable number of boxes and I'd like to display as many as I can without forcing the viewer to scroll horizontally, there should also be a certain space in between them. This means that the boxes will have to move to the next or previous "row" if the browser is resized.

How do I achieve this using divs and CSS?

Thanks in advance :-)

P.S: Enjoy my fine art skills:

alt text

+4  A: 

All you need to do is setting the red divs width and/or height as "percentage" and setting your small-black divs float: left.

Example:

<div style="width: 80%"><div style="margin: 5px 0px 5px 10px; float: left;"></div> </div>

This will let your red div resize as soon as viewer resizes the window.>

scaryguy
You don't need to apply any special style to the outer `<div>`, and it will automatically take up the width of the page (or whatever its parent element is).
Matt Huggins
It seems like my container, the outside div, ignores the rows and height of the boxes inside. It has the 80% width but it's not vertically stretching... Hmm. It works other than that.
Chris
Make sure that, your red div is set positioned "relative". If you want your div extend dynamicly you shouldn't set height of it. Leave it blank.
scaryguy
@Chris: add `<div style="clear: both;"></div>` inside your container, after the last box. That should fix it ;)
FreekOne
+2  A: 

Scaryguy's is answer pretty much correct. But the outer div should have overflow: hidden for the conteiner to work properly.

See this example: http://jsfiddle.net/QCf4U/

cssexample

The code in the example has all the red boxes with float: left. And there are 4 blue divs that contain (the first 2 blue divs are stuck together on the top):

  1. No clear and no float, and has 3 red divs inside
  2. No clear and no float, and has 3 red divs inside
  3. Has clear: left, and 5 red divs inside
  4. Has overflow: hidden, and 5 red divs inside

Notice that without clear nor float nor overflow: hidden on the container, your red divs on container 1 and 2 will be next to each other (not following the container).

You can see that for the container blue div to get its correct vertical size you have to use overflow: hidden (or maybe float there too).

Protron
I'm pretty sure `overflow: hidden` is a better solution for clearfixes
Yi Jiang
You don't have to use a float. You can use an overflow:hidden, you can use a clearfix, and hasLayout triggering for IE.
meder
Oh, you are right guys. I didn't know about overflow:hidden. I will fix my anwser. Thanks!
Protron
Yep, overflow:hidden did the trick. Who knows how to let the divs stretch individually depending on the contents? Let's say div #3 has a really long line in it, what style do I apply to make sure the div stretches for it?
Chris