Reputation: 12007
I've been trying this for a while with no luck. I have a parent <div>
tag (lets say it's set to 300px
in width). I am trying to add a series of smaller <div>
tags to go inside the parent, and be placed side by side until the edge of the parent <div>
where the next child <div>
will then be placed on the "next line". Basically, I am trying to make these child <div>
tags act like words being word wrapped.
I have googled this like crazy, but I can't find any way to really do this without calculating the sizing of everything and manually placing the child <div>
's with absolute coordinates, which I can do, but I'd like to avoid. Sp first, I was wondering if there was a css
or javascript
approach that could supply the same behavior.
The number of child divs is variable, and I am using C# server side code to calculate them. But it shouldn't matter which server language I'm using.
Thanks!
Upvotes: 0
Views: 993
Reputation: 133
Floating is a totally reasonable way to do it.
Alternatively you could use elements with CSS display:inline or display:inline-block . Both are automatically positioned by the browser as you describe, side-by-side and "wrapping" when they run out of space. The difference is that inline elements don't give you as much control over padding, dimensions etc., whereas inline-block elements give you all the perks of a display:block element. However IE6 does have some difficulty with inline-block elements, as I recall, which is irritating.
If you want to use inline elements, just switch your child divs to spans: spans are inline by default, no further work necessary. However there are no elements that display inline-block by default, so if you need to use this you may as well keep your divs.
Hopefully you have some options there.
Upvotes: 1
Reputation: 10179
Try this:
Use display: inline-block;
HTML:
<div id="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
CSS:
html, body { height: 100%; }
#parent {
background-color: lightblue;
width: 300px;
height: 100%;
}
.child {
width: 50px;
height: 100px;
display: inline-block;
background-color: red;
}
<hr>
<h2>Approach 2</h2>
Use float: left;
HTML:
<div id="parent">
<div id="child"></div>
<div id="child"></div>
<div id="child"></div>
<div id="child"></div>
<div id="child"></div>
<div id="child"></div>
</div>
CSS:
html, body { height: 100%; }
#parent {
background-color: lightblue;
width: 300px;
height: 100%;
}
#child {
width: 50px;
height: 100px;
float:left;
background-color: red;
margin: 2px;
}
Upvotes: 2