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;
}
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;
}
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With