css float elements with unequal heights left and u

2019-01-14 01:23发布

I'm wondering how I can accomplish the effect in figure 1.

Float left up

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.

3条回答
再贱就再见
2楼-- · 2019-01-14 01:59

Since you are already using jquery, jquery masonry might interest you: http://masonry.desandro.com

查看更多
做自己的国王
3楼-- · 2019-01-14 02:07

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.

查看更多
做自己的国王
4楼-- · 2019-01-14 02:12

Well, if you only aim to support the most modern browser, the CSS3 multi-column layout could help. One problem with this approach is that it will not keep the same order, but you can play with the order in the HTML (or Javascript).

I added a container around your spans called #container.

#container { 
    -webkit-column-width: 100px; 
    -moz-column-width: 100px; 
    column-width: 100px; 
}

jsFiddle Demo

查看更多
登录 后发表回答