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

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

Code
Demo

The basic form of HTML looks like this:

4条回答
  •  青春惊慌失措
    2020-12-21 23:51

    Based on @Thomas's answer, I've identified two possible solutions. I am going with the #2 solution considering better browser support for it.


    1. Using the unit vh (viewport height). Browser support: IE9 and above.

    CSS:

    .home #primary { /* Parent */
        display: table;
        width: 100%;
    }
    
    .home #main { /* Child */
        display: table-cell;
        height: 100vh; /* 100% viewport height */
        vertical-align: middle;
    }
    

    2. Dynamically setting height of parent (.home #primary) equal to that of browser's viewport.

    JS:

    jQuery(document).ready(function($){
    
        var window_h = $(window).height();
        var jumbotron_h = $('.home #main').height();
    
        if (window_h <= (jumbotron_h + 60)) {
            var window_h = jumbotron_h + 60
        }
    
        $('.home #primary').attr('style', 'height:'+window_h+'px;');
    
    });
    

    CSS:

    .home #primary { /* Parent */
        display: table;
        width: 100%;
    }
    
    .home #main { /* Child */
        display: table-cell;
        height: 100%; /* 100% height of parent */
        vertical-align: middle;
    }
    

提交回复
热议问题