0

I'm looking for a way to automatically fill in a div with width x1 and height y1 with other div elements, each with width x2 and height y2

So the html would look like:

<div class="parentdiv">
    <div class="subdiv"></div>
    <div class="subdiv"></div>
    <div class="subdiv"></div>
    ...
</div>

The subdivs are appended dynamically, based on how many are needed to display all the information. I want them to fill up the space in the parentdiv horizontally and then move to the next row when they hit the edge.

Right now they just stack below one another vertically and there is a lot of wasted space. Is there a cross-browser solution for this?

1
  • What are you really trying to do? You speak of wasted space? Are .subdiv populated?
    – vol7ron
    Apr 19, 2012 at 19:34

2 Answers 2

2
<style type="text/css">
    .parentdiv .subdiv { display: inline-block; }
</style>

Note that IE7 has problems with div's going inline, so you may need to make those subdivs, subspans (still using inline-block);


Or Brian's solution of float:left;

3
  • thank you for your quick response and it worked perfectly. Not sure who to give the answer credit to since both methods work :/ Apr 19, 2012 at 19:58
  • If you use this solution you're going to have whitespace between the two <div> elements because they are now inline-level and not block-level. If you remove any space between their tags as such ----------- > </div><div class="subdiv"> you will also remove the undesired space between the two elements. I would argue that this is the better way of doing it.
    – Wex
    Apr 19, 2012 at 19:59
  • 1
    @Wex: that's a good point. you might be able to do .parentdiv {white-space-collapse: discard;}, but since it hasn't really been supported. I side with your method.
    – vol7ron
    Apr 19, 2012 at 20:14
1

By default, a div will take up the entire width of its parent container. You can fix this by adding a float: left to your subdiv class. Just make sure you clear the floats at the end of your container. Something like this:

<style type="text/css">
.parentdiv .subdiv { float: left; }
</style>

<div class="parentdiv">
    <div class="subdiv"></div>
    <div class="subdiv"></div>
    <div class="subdiv"></div>
    ...
    <div style="clear: both;"></div>
</div>
2
  • thank you for your quick response, worked perfectly, not sure who to give answer credit too since vol7ron's also worked :/ Apr 19, 2012 at 19:58
  • If Dougie's works how you intended, use his solution (IE sometimes struggles with inline-block). I just wanted to offer an alternative, since float can also be problematic in some layouts.
    – vol7ron
    Apr 19, 2012 at 20:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.