I have got a couple of boxes containing text which should be displayed next to each other. They all have a fixed width, but a variable height (depending on their content). They are inside of a container with a variable width.
If there are too many boxes I want them to jump into the next line and start from the left again. I realized this using left floated boxes. This causes a problem if the first box per line is higher than the next one, because then the ones from the new line won’t start from the left. Here’s a demo:
HTML:
<section>
<article>One: This text is so long, it's so long oh my gosh!</article>
<article>Two</article>
<article>Three: bla bla bla bla bla bla bla bla</article>
<article>Four</article>
</section>
CSS:
section{
width: 300px; /* For demo, this can vary */
overflow: hidden;
}
article{
float: left;
width: 100px;
background: #dddddd;
padding: 10px;
margin: 10px;
}
You can also have a look at this JSFiddle, where you can see the problem immediately: http://jsfiddle.net/dwr6K/ Box “Three” starts right from Box “One”, although I’d like it to start in the new line under Box “One”. Sadly I can’t use clear: left because I don’t know how many boxes will fit in a line.
Is there a way to prevent this and to display it the way I’d like to?
Here: http://jsfiddle.net/dwr6K/9/
Just remove
float: left;and add
to
article.As @JimmyX pointed out, do go through this post about Cross-Browser Inline-Block
Basically, what
float:leftdoes is it makes each element stick next to the leftmost div it can find. And hence if the heights vary, you don’t get the desired layout.