Making an element fill the entire height of browser viewport using jQuery

前端 未结 4 411
青春惊慌失措
青春惊慌失措 2020-12-21 23:28

Code
Demo

The basic form of HTML looks like this:

4条回答
  •  礼貌的吻别
    2020-12-22 00:04

    First off, Jquery's .outerheight() function includes padding, which means that when you measure the height of your #Main element after this function runs the first time, it will equal the window.height. In other words - it will look awful when you resize your browser. You can see this in action on this fiddle when you resize the browser window the old-fashioned way. You can use margins instead, but then you'll have to adjust your CSS quite a bit. Even then, resizing the window still looks awful and buggy and has inconsistent results across browsers. You can see that on this fiddle.

    The specific bug you're referring to is probably due to inconsistent math when you resize your window - a combination of your use of padding (which is included in .outerheight() as mentioned above) and the viewport size not being easily divisible by 2 (it's impossible to have half a pixel and different browsers will render that half a pixel differently).

    I should also point out this line of code:

    if (window_h > (jumbotron_h + 60)) {
        var jumbotron_padding = (window_h - jumbotron_h)/2
    } else {
        var jumbotron_padding = 30
    }
    

    This forces your page to always be #main.height() + 60, which can be bigger than your viewable window, depending upon your window size. #main.height() comes out to around 200.5px (there we are with another half pixel).

    Assuming that your goal is to vertically center the #Main element, your best bet is to use one of the many straight CSS methods available. The table method seems most applicable here because it is completely dynamic (and thus can be responsive) - simply create a single cell CSS table, use CSS valign, and build your entire page inside that cell. For older versions of IE you'll need to use a tiny hack (display:Inline-block;) to make it work.

    HTML:

    Content here

    CSS:

    #parent {display: table;}
    
    #child {
        display: table-cell;
        vertical-align: middle;
    }
    

    IE fix:

    #child {
        display: inline-block;
    }
    

提交回复
热议问题