可变高度的浮动元素推动兄弟姐妹向下

时间:2013-02-26 20:04:15

标签: html css

我有6个元素,每个元素应该产生两行,每行3个元素,所以我已经浮动了它们。但是元素的内容变化很大,当一个较高的元素阻止后续的兄弟姐妹一直漂浮时,布局会中断:

Floated elements breaking layout

以下是CSS示例:

figure { width: 30%; float: left; margin-left: 1%; font-size: small; outline: solid #999 1px; }
img { max-width: 100%; }

和HTML:

<figure>
  <img src="http://placekitten.com/150/200?image=1" alt="Kitten 1" />
  <figcaption>Bacon ipsum dolor sit amet short ribs pork chop pork belly spare ribs shoulder tri-tip beef ribs turkey brisket short loin tenderloin ground round. </figcaption>
</figure>
<figure>
  <img src="http://placekitten.com/150/200?image=2" alt="Kitten 2" />
  <figcaption>Short ribs cow corned beef, beef tenderloin swine biltong short loin. </figcaption>
</figure>
<figure>
  <img src="http://placekitten.com/150/200?image=3" alt="Kitten 3" />
  <figcaption>Boudin chuck ground round, pig pastrami salami turkey ham hock beef ribs tongue. </figcaption>
</figure>
<figure>
  <img src="http://placekitten.com/150/200?image=4" alt="Kitten 4" />
  <figcaption>Tri-tip pork loin tongue corned beef shankle ball tip. </figcaption>
</figure>
<figure>
  <img src="http://placekitten.com/150/200?image=5" alt="Kitten 5" />
  <figcaption>Turkey swine tenderloin spare ribs sausage filet mignon hamburger. Leberkas andouille prosciutto, bresaola tri-tip short loin meatloaf shank pig shoulder spare ribs ribeye. </figcaption>
</figure>
<figure>
  <img src="http://placekitten.com/150/200?image=6" alt="Kitten 6" />
  <figcaption>Pastrami andouille tongue tri-tip jerky.</figcaption>
</figure>

一个例子JSFiddle:http://jsfiddle.net/KatieK/5Upbt/

如何让第二行figure元素排在前3个元素下方?

HTML / CSS解决方案优于JavaScript / jQuery解决方案。

3 个答案:

答案 0 :(得分:2)

仅限CSS解决方案怎么样?添加此规则:

figure:nth-of-type(3n+1) {
    clear:left;
}

<强> jsFiddle example

答案 1 :(得分:2)

您可以使用:nth-child伪类清除每个第四个元素。

figure:nth-child(4n){clear: left;}

编辑:

4n并没有完全削减它。 3n + 1就是你想要的。

figure:nth-child(3n + 1){clear: left;}

http://jsfiddle.net/jMCng/1/

答案 2 :(得分:2)

以下是我测试的解决方案:http://jsfiddle.net/5Upbt/7/

我修改你的数字风格

figure { display: inline-block; vertical-align: top; width: 30%; margin-left: 1%; font-size: small; outline: solid #999 1px; }

这是基于更通用的解决方案:http://jsfiddle.net/bazmegakapa/Ft9d2/