css浮动元素在网格中左右高度不等 [英] css float elements with unequal heights left and up in grid

查看:16
本文介绍了css浮动元素在网格中左右高度不等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何实现图 1 中的效果.

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

到目前为止我得到的是

<代码>.box { 显示:内联块;垂直对齐:顶部;宽度:100px;}

这给了我图 2 所示的结果.(注意:我知道我可以用 float: left 完成同样的事情)

This gives me the result illustrated in figure 2. (Notice: I'm aware I can accomplish the same with float: left)

我的 HTML 代码如下所示:

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.

是否可以用纯 css 来做到这一点,或者我需要一些 javascript?

Is it possible to do this with pure css, or will i need some javascript?

将整个网格定位到页面的中心对我来说很重要.这就是我使用 display:inline-block 的原因.网格也不应该固定在页面上,因为我希望它在调整窗口大小时重排.

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.

推荐答案

您可以使用流行的库Masonry.

jQuery 的动态布局插件 CSS 浮动的另一面

A dynamic layout plugin for jQuery The flip-side of CSS floats

这是一个代码示例...

$('#container').masonry({
  itemSelector: '.box'
});

这是 Github 上的来源和对 David Desandro.

Here is the source on Github and an interview with David Desandro on the Shoptalk podcast.

对于不使用 jQuery 的人,请注意还有 Vanilla Masonry,这是无框架版本.

For folks that aren't using jQuery, note that there's also Vanilla Masonry which is the framework-free version.

提示:确保父容器具有 position:relative 以便所有内容都绑定到您的容器.

Tip: Make sure the parent container has position:relative so all the content is bound to your container.

这篇关于css浮动元素在网格中左右高度不等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆