JQuery: dynamic height() with window resize()

前端 未结 4 1660
再見小時候
再見小時候 2021-01-31 05:00

I\'m having an issue identical to this poster: Jquery problem with height() and resize()

But the solution doesn\'t fix my issue. I have three stacked divs, and I want to

相关标签:
4条回答
  • 2021-01-31 05:08

    To see the window height while (or after) it is resized, try it:

    $(window).resize(function() {
    $('body').prepend('<div>' + $(window).height() - 46 + '</div>');
    });
    
    0 讨论(0)
  • 2021-01-31 05:09

    I feel like there should be a no javascript solution, but how is this?

    http://jsfiddle.net/NfmX3/2/

    $(window).resize(function() {
        $('#content').height($(window).height() - 46);
    });
    
    $(window).trigger('resize');
    
    0 讨论(0)
  • 2021-01-31 05:15

    The cleanest solution - also purely CSS - would be using calc and vh.

    The middle div's heigh will be calculated thusly:

    #middle-div { 
    height: calc(100vh - 46px); 
    }
    

    That is, 100% of the viewport height minus the 2*23px. This will ensure that the page loads properly and is dynamic(demo here).

    Also remember to use box-sizing, so the paddings and borders don't make the divs outfill the viewport.

    0 讨论(0)
  • 2021-01-31 05:20

    Okay, how about a CSS answer! We use display: table. Then each of the divs are rows, and finally we apply height of 100% to middle 'row' and voilà.

    http://jsfiddle.net/NfmX3/3/

    body { display: table; }
    div { display: table-row; }
    #content {
        width:450px; 
        margin:0 auto;
        text-align: center;
        background-color: blue;
        color: white;
        height: 100%;
    }
    
    0 讨论(0)
提交回复
热议问题