Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make floating divs the same height

Tags:

html

css

I have 2 divs side by side. I don't know the height of them upfront, it changed according to the content. Is there a way to make sure they will always be the same height, even when one of them stretches, only with CSS?

I made a fiddle to show. I want the red and blue divs to be the same height...

http://jsfiddle.net/7RVh4/

this is the 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;
}
like image 540
Moshe Shaham Avatar asked May 01 '13 11:05

Moshe Shaham


2 Answers

You could try instead of using float, use display: table-cell. You might find some older browsers don't understand this rule however. See below:

#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;
}
like image 167
antony Avatar answered Oct 26 '22 02:10

antony


Antony answer works ok, but you need all the divs to have the same parent and to have a wrapper, I have a solution that use javascript but works with any kind of element, they just need to have the same selector.

  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/

like image 33
luisZavaleta Avatar answered Oct 26 '22 03:10

luisZavaleta