使浮动div具有相同的高度

时间:2013-05-01 11:41:54

标签: html css

我有两个div并排。我不知道他们的前期高度,它根据内容改变。有没有办法确保它们总是在同一个高度,即使其中一个伸展,只有CSS?

我做了个小提示。我希望红色和蓝色的div具有相同的高度......

http://jsfiddle.net/7RVh4/

这是css:

#wrapper {
width: 300px;
}
#left {
    width:50px;
    background: blue;
    float:left;
    height: 100%;  /* sadly, this doesn't work... */
}
#right {
    width:250px;
    background: red;
    float:left;
}

5 个答案:

答案 0 :(得分:25)

您可以尝试使用display: table-cell而不是使用float。您可能会发现一些旧版浏览器不理解此规则。见下文:

#wrapper {
    display: table; // See FelipeAls comment below
    width: 300px;
}

#left {
    display: table-cell;
    width: 50px;
    background: blue;
}

#right {
    display: table-cell;
    width: 250px;
    background: red;
}

答案 1 :(得分:5)

Antony的答案工作正常,但你需要所有的div拥有相同的父级并拥有一个包装器,我有一个使用javascript的解决方案,但适用于任何类型的元素,他们只需要有相同的选择器。 / p>

  function setEqualHeight(selector, triggerContinusly) {

    var elements = $(selector)
    elements.css("height", "auto")
    var max = Number.NEGATIVE_INFINITY;

    $.each(elements, function(index, item) {
        if ($(item).height() > max) {
            max = $(item).height()
        }
    })

    $(selector).css("height", max + "px")

    if (!!triggerContinusly) {
        $(document).on("input", selector, function() {
            setEqualHeight(selector, false)
        })

       $(window).resize(function() {
            setEqualHeight(selector, false)
       })
    }


}

    setEqualHeight(".sameh", true) 

http://jsfiddle.net/83WbS/2/

答案 2 :(得分:2)

我建议阅读这篇文章,解释如何做你想做的事情。我会说一个小提琴,但它相当广泛和纯粹的CSS。 http://matthewjamestaylor.com/blog/equal-height-columns-cross-browser-css-no-hacks

答案 3 :(得分:0)

我想指出一个更简单的解决方案。在列上使用相同金额的大v和否定padding-bottom: 500em,而包装器只需margin-bottom:-500em即可将列剪切为正确的大小。

在这里找到: HTML/CSS: Making two floating divs the same height

答案 4 :(得分:-3)

使用this CSS技巧,您可以在不使用表的情况下执行此操作。

示例 - http://jsfiddle.net/LMGsv/

<强> HTML

   <div id="wrapper">
            <div id="columns">
                <div id="left">text</div>
                <div id="right">text<br/>another line<br /></div>
            </div>        
    </div>

<强> CSS

#wrapper {
    float:left;
    width: 300px;
}
#columns {
    float:left;
    width:300px;
    background:blue;
}
#left {
    float:left;
    width:50px;
    background: blue;
}
#right {
    width:250px;
    background: red;
    float:left
}