【问题标题】:Floated elements of variable height push siblings down可变高度的浮动元素将兄弟姐妹向下推
【发布时间】:2013-02-12 10:35:45
【问题描述】:

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

这里是 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 个数字包装在一个 DIV 中?
  • +1 获取可爱的小猫照片。您需要使用 css clear: left 再次开始向左浮动。
  • @BradM 不会把所有的数字都推到左边吗?
  • @KatieK 我认为你要么按照 One Trick Pony 的建议去做,要么像 Pinterest 那样使用 jQuery 来定位它们。

标签: html css


【解决方案1】:

纯 CSS 解决方案怎么样?添加这条规则:

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

jsFiddle example

【讨论】:

    【解决方案2】:

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

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

    编辑:

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

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

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

    【讨论】:

    • @j08691 你是对的。 (4n) 没有给出 3 行。我已经更新了它和要使用的小提琴 (3n + 1)
    • 你确定?对我来说,这就像一排排 3 只小猫。
    • 对不起。现在很好。不知道上次查的时候在想什么。
    【解决方案3】:

    这是我测试的解决方案: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/

    【讨论】:

    • FWIW,我不想将图形元素锁定到特定大小。
    猜你喜欢
    • 2019-03-27
    • 1970-01-01
    • 2017-02-16
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多