【问题标题】:CSS two columns with known children widthCSS具有已知子宽度的两列
【发布时间】:2011-05-14 16:27:37
【问题描述】:

我创建了一些代码来显示具有不同高度的框(高度将来自内部的图像)。

在这个例子中完美运行:http://jsfiddle.net/GSnfG/

...但是当我编辑一些高度(将来 - 图像的高度)here: box 3 set to height 100px 时,结果并不好。

如何准备 CSS 代码来创建类似两列的内容?

我不能使用表格,也不想使用 jquery 或其他 js 有可能吗?

【问题讨论】:

  • 是的,可以使用 CSS 和 HTML。请参阅下面的答案。

标签: css css-float


【解决方案1】:

不,如果没有 JavaScript 或服务器端语言,在一般情况中无法处理此问题。

在某些情况下,您可以为每个单独的列添加包装器divs,但是元素大小的某些组合会使这看起来很糟糕,例如:http://jsfiddle.net/suaaK/3/ - 在那个演示中,如果使用 Box 可能会更好6 在方框 3 下。您拥有的元素越多(并且大小不同),列可能变得越不均匀。

查看此答案以比较候选技术,显示它们不起作用,并显示解决方案的客户端部分涉及服务器端代码:

如果你愿意使用 JavaScript+jQuery,你应该使用jQuery Masonry

还有一个原始的 JavaScript 版本:Vanilla Masonry

演示:

【讨论】:

  • 我必须同意你的回答。正如您在 jsFiddle 演示中所描述的那样,它看起来很奇怪。也就是说,如果@kicaj 更担心拥有同样平衡的框/图像而不关心是否使用 Javascript。
【解决方案2】:

我通过jFiddle 提供了一个可能的解决方案的示例

首先创建两列,一列用于左侧框,一列用于右侧框。见下文。

如果您担心 box-container 的宽度,只需将 .box-container {width:105px} 添加到您的 CSS。

 <div class="container">
        <div class="left box-container">
            <div class="box" style="height:60px;">1</div>

            <div class="box" style="height:100px;">2</div>

            <div class="box" style="height:60px;">3</div>

        </div><!-- left-box-container -->

        <div class="right box-container">
            <div class="box" style="height:30px;">1</div>

            <div class="box" style="height:200px;">2</div>

            <div class="box" style="height:60px;">3</div>

        </div><!-- right-box-container -->

    </div>

【讨论】:

    【解决方案3】:

    如果你想让列最终具有相同的高度,也就是说,填充比它们的邻居更小的 div,你可以将 css 更改为如下所示:

    .box {background:#20abff; color:#fff; width: 5px; margin: 5px;}
    .left {float:left;}
    .right {float:left;}
    .container {width:200px;}
    

    您可以做的另一件事是使用 div 制作伪表格。

    .Table_Wrapper { width: 400px; }
    .Table_Row { width: 98%; padding: 1%;float: left; } 
    
    
    <div class="Table_Wrapper">
        <div class="Table_Row">
            <div class="box left" style="height:60px;">1</div>
            <div class="box right" style="height:80px;">2</div>
        </div>
        <div class="Table_Row">
            <div class="box left" style="height:60px;">3</div>
            <div class="box right" style="height:60px;">4</div>
        </div>
        <div class="Table_Row">
            <div class="box left" style="height:60px;">5</div>
            <div class="box right" style="height:60px;">6</div>
        </div>
    </div>
    

    JSFiddle

    【讨论】:

    • 如果做一个伪表格,那么看CSS的显示:table
    • display: table 在浏览器中不受支持,否则我会
    猜你喜欢
    • 2020-11-30
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 2021-02-20
    • 1970-01-01
    相关资源
    最近更新 更多