I'm wondering how I can accomplish the effect in figure 1.
What I have got so far is
.box { display: inline-block; vertical-align: top; width: 100px;}
This gives me the result illustrated in figure 2. (Notice: I'm aware I can accomplish the same with float: left)
My HTML code looks something like this:
<span class="box">A<br><br><br><br></span> <span class="box">B<br></span> <span class="box">C<br><br><br></span> <span class="box">D<br><br><br></span> <span class="box">E<br><br><br><br><br><br></span> <span class="box">F</span> <span class="box">G<br><br><br><br></span> <span class="box">H<br></span> <span class="box">I<br><br></span>
I want every element to be floated to the left as far as possible, but meanwhile floating upwards.
Is it possible to do this with pure css, or will i need some javascript?
EDIT:
It is important for me that the entire grid is positioned to the center of the page. That's why I use display:inline-block. The grid should also not be fixed to the page because I want it to reflow when I resize my window.
The CSS clear property moves down the element when any floating comes to disturb the element. You can use the “none,” “left,” “right,” “both,” “initial,” and “inherit,” “inline-start,” “inline-end” keywords value. The “left” value moves down the element to avoid the past left floating.
To clear a float, add the clear property to the element that needs to clear the float. This is usually the element after the floated element. The clear property can take the values of left , right , and both . Usually you'll want to use both.
The elements after the floating element will flow around it. The elements before the floating element will not be affected. If the image floated to the right, the texts flow around it, to the left and if the image floated to the left, the text flows around it, to the right.
You can use the popular library Masonry.
A dynamic layout plugin for jQuery The flip-side of CSS floats
Here is a code example...
$('#container').masonry({ itemSelector: '.box' });
Here is the source on Github and an interview with David Desandro on the Shoptalk podcast.
For folks that aren't using jQuery, note that there's also Vanilla Masonry which is the framework-free version.
Tip: Make sure the parent container has position:relative so all the content is bound to your container.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With