Fill vertically

by balefrost

HTML

<div id='container'>
    <div id='before'></div>
    <div id='wrapper'>
        <div id='above'></div>
        <div id='target'></div>                    
        <div id='below'></div>
    </div>           
    <div id='after'></div>
</div>

CSS

#container {
    overflow: hidden;
    resize: vertical;
    height: 100px;
    border: 3px solid green;
}

#before, #above, #wrapper, #below, #after {
    border: 1px solid red;
}

#wrapper {
    margin: 10px;
}

#before {
    background-color: #fa0;
    height: 20px;
}

#above {
    background-color: #fd0;
    height: 30px;
}

#below {
    background-color: #0fd;
    height: 40px;
}

#after {
    background-color: #0fa;
    height: 50px;
}

#target {
    margin: 10px;
    border: 20px solid black;
    height: 10px;
    background-color: red;
    min-height: 100px;
}

JavaScript

var container = $('#container');
//container = window;

var oldHeight = container === window ? window.innerHeight : container.innerHeight();

setInterval(function() {
    var newHeight = container === window ? window.innerHeight : container.innerHeight();
    if (newHeight !== oldHeight) {
        oldHeight = newHeight;
        resized();
    }
}, 33);

function cssPixels(value) {
    return parseInt(value.match(/(\d+)px/)[1], 10)
}

function resized() {
    var target = $('#target');
    var contentTop = target.offset().top;
    var contentBottom = contentTop + target.innerHeight();
    
    var firstTop, lastBottom;
    if (container === window) {
        firstTop = 0;
        lastBottom = $(document.body).outerHeight(true);
    } else {
        var first = container.children().first();
        firstTop = first.offset().top - cssPixels(first.css('margin-top'));
        
        var last = container.children().last();
        lastBottom = last.offset().top + last.outerHeight(false) + cssPixels(last.css('margin-bottom'));
    }
    
    var topSpan = contentTop - firstTop;
    var bottomSpan = lastBottom - contentBottom;
    
    var heightAvailable = container === window ? window.innerHeight : container.innerHeight();
    
    console.log(firstTop, contentTop, contentBottom, lastBottom);
    console.log(topSpan, bottomSpan, '/', heightAvailable);

    target.height(heightAvailable - topSpan - bottomSpan); 
}