【问题标题】:modify html/css code with pure css, without any html modifications to align divs用纯 css 修改 html/css 代码,无需任何 html 修改来对齐 div
【发布时间】:2014-02-10 17:23:24
【问题描述】:

一个大 div 中有很多<div style="float:left;"></div>

http://jsfiddle.net/h3EY9/1/

因此,宽度相同但高度可能不同(取决于里面的文字)。 是否可以对齐 divs 使其看起来不错 - 它连续 3 个。 这意味着,它看起来像 this http://jsfiddle.net/h3EY9/1/ 或这样:

123
456
789
...

仅使用 css?

html 解决方案:我可以将每 3 个 div 包装到 <div style="overflow:hidden;"></div> 中,例如 here http://jsfiddle.net/h3EY9/1/,但是我不允许修改 html 代码,html 解决方案不是可取的。我很好奇是否可以使用纯 CSS 解决方案。 谢谢。

【问题讨论】:

    标签: css html css-float height


    【解决方案1】:

    您可以为每三分之一的<div> 添加clear:left

    .inner-div:nth-child(3n+1){ clear:left; }
    

    http://jsfiddle.net/h3EY9/4/

    更多关于 MDN 上的nth-child

    【讨论】:

    • 如果您必须支持 IE8 及以下版本,您可能需要一些额外的解决方案。
    • 是的,我已经检查过它不适用于 IE8-。谢谢你指出!
    • 当然,您的解决方案有效,但我认为,使用 inline-block 的方式会更好一些。一切都取决于他的目标......
    【解决方案2】:

    为您的 div 使用 display: inline-blockvertical-align。并删除 wrapper-divs。看到这个Demo-Fiddle

    .inner-div{
        display: inline-block;
        vertical-align: top;
        border:1px solid green;
        margin: 2px;
        position: relative;
        width: 140px;
        min-height:50px;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-02-16
      • 1970-01-01
      • 1970-01-01
      • 2012-02-21
      • 2022-11-16
      • 2013-11-09
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多