CSS列表如

时间:2011-02-07 11:47:05

标签: html css

在当天,当表格用于布局内容设置时,列式布局很容易.I <table><tr><td>column 1</td><td>Column2</td></table>

我正在尝试使用CSS(使用Div等)来做同样的事情,但是,我在尝试保持两个相同大小的列时遇到了困难。以下是我所谈论的一个例子:http://www.jsfiddle.net/ybYJ9/

我要做的是让左侧的列(标记为蓝色)与右侧的列具有相同的大小。右侧列的高度将根据内容大小增加,因此无法修复大小。我已经尝试将列高设置为100%,如果你可以帮忙解决这个问题就不行了。

由于

5 个答案:

答案 0 :(得分:2)

最常用的方法是“Faux Columns”。 您可以将较短列的背景图像/颜色应用于整个容器。容器将拉伸到更高的列,所以看起来它们具有相同的高度。 第二种方式是背景,看起来像两个列,你将垂直重复它。如果你不知道哪个列会更高,它会很好用。

答案 1 :(得分:2)

最好的方法是使用like this

使用jQuery(或类似的脚本语言)来检测主div的高度并将值传递给其他div:)

答案 2 :(得分:0)

目前在CSS中没有一种清晰安全的方法。

您可以:

  1. 使用faux columns - 如果设计允许
  2. 使用display: tabledisplay: table-rowdisplay: table-cell,有效地将语义标记呈现为表格。 Here's some details about this,但要警惕,doesn't work in
  3. Use JS to set equal heights to the columns. You can do this manually (comparing the height of each column, and setting each column's height to be that of the tallest), or simpler via a jquery plugin。 如果您依赖JS,请注意动态高度更改,因为您必须更新先前设置的height声明。

答案 3 :(得分:0)

有很多方法可以做到,而且对我来说都不是100%令人满意。 Rebelek的答案很好,但我最喜欢的方法是使用jQuery插件。

(function ($) {
    $.fn.equalColumnHeights = function () {
        equalise = function (element) {
            var maxHeight = 0;
            $(element).children().each(function() {
                if ($(this).height() > maxHeight) {
                    maxHeight = $(this).height();
                }
            });
            $(element).children().height(maxHeight);
        };
        return this.each(function () {
            equalise(this);
            var element = this;
            $(window).resize(function () {
                $(element).children().height('');
                equalise(element);
            });
        });
    };
}(jQuery));

然后在你的例子中:

jQuery(function ($) {
    $('#mainBody').equalColumnHeights();
});

此处示例:http://www.jsfiddle.net/nathan/ybYJ9/9/除了添加上述JavaScript之外,我没有更改任何内容。这就是我喜欢这种方法的原因:完全不侵入。

答案 4 :(得分:0)

如果不使用JS,则无法将两个不同的div元素设置为相同的非固定高度。 但是,您可以尝试使用CSS display 属性模拟表行为。 查看这3个属性:

display: table;
display: table-row;
display: table-cell;

为外部div设置 display:table (其行为类似HTML&lt; table&gt;标记) 对于您的行,请使用 display:table-row ,对于表格单元格,请使用 display:table-cell

你会有这样的事情:

<div style="display: table;">
  <div style="display: table-row;">
    <div style="display: table-cell;">
      1 cell
    </div>
    <div style="display: table-cell;">
      2 cell
    </div>
  </div>
</div>

但请注意,因为并非所有浏览器都能正确处理这些属性。 希望它有所帮助。